码迷,mamicode.com
首页 > 其他好文 > 详细

24. Swap Nodes in Pairs

时间:2018-10-05 22:34:58      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:int   ons   node   public   div   val   pac   const   swap   

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 

 

24. Swap Nodes in Pairs

标签:int   ons   node   public   div   val   pac   const   swap   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9746036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!