24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

AC code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode **dummy = &head, *a, *b;
        while ((a=*dummy) && (b=a->next)) {
            a->next = b->next;
            b->next = a;
            *dummy = b;
            dummy = &(a->next);
        }
        return head;
    }
};

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Swap Nodes in Pairs.

  

1 2 3 4 5 6 
a       
  b   
  3 1                                                                          
 *pp 
                    pp->2->1->
  a b                  (b)(a)
    4 3                   *pp 
   *pp 
                           pp->4->3->
    a b                       (b)(a)
      5 4                        *pp 
     *pp
                                 pp->6->5
      a b                           (b)(a)
        6 5                            *pp 
         *pp 
永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/9746036.html