zoukankan      html  css  js  c++  java
  • [LeetCode] Swap Nodes in Pairs

    Well, since the head pointer may also been modified, we create a new_head that points to it to facilitate the swapping process.

    For the example list 1 -> 2 -> 3 -> 4 in the problem statement, it will become 0 -> 1 -> 2 -> 3 -> 4 (we init new_head -> val to be 0). Then we set a pointer pre to new_head and anothercur to head. Each time, we will swap pre -> next and cur -> next using the following piece of code.

    pre -> next = cur -> next;
    cur -> next = cur -> next -> next;
    pre -> next -> next = cur;

    After swapping them, we update as follows:

    pre = cur; 
    cur = pre -> next; 

    to swap the next two nodes.

    Finally, we return new_head -> next.

    The complete code is as follows.

     1 class Solution {
     2 public:
     3     ListNode* swapPairs(ListNode* head) { 
     4         if (!head || !(head -> next)) return head;
     5         ListNode* new_head = new ListNode(0);
     6         new_head -> next = head;
     7         ListNode* pre = new_head; 
     8         ListNode* cur = head;
     9         while (pre -> next && cur -> next) {
    10             pre -> next = cur -> next;
    11             cur -> next = cur -> next -> next;
    12             pre -> next -> next = cur;
    13             pre = cur;
    14             cur = pre -> next;
    15         }
    16         return new_head -> next;
    17     }
    18 };
    
    
  • 相关阅读:
    开发PHP扩展(一)
    ssh 使用技巧
    安装scribe
    PHP扩展中定义一个类
    PHP扩展的加载流程
    PHP扩展中访问全局变量$_POST,$_GET,$_SERVER等
    PHP的HashTable(一)
    PHP的HashTable(二)
    MVC ScriptBundle自定义排序。
    解决bootstrap和easyUI部分css类冲突问题。
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4624281.html
Copyright © 2011-2022 走看看