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 };
    
    
  • 相关阅读:
    Linux下安装confluence汉化破解版
    某种可以解决一切问题的方法
    普通平衡树(treap)
    文艺平衡树(splay模板)
    [CQOI2015]任务查询系统
    [NOIP2016]天天爱跑步
    NOI2018_Day1_T1_归程
    Picture
    bzoj3524 Couriers
    bzoj2588 counting on a tree
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4624281.html
Copyright © 2011-2022 走看看