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

Swap Nodes in Pairs

时间:2019-08-27 01:15:11      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:const   odi   tno   style   ret   next   use   lis   values   

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.
class Solution{
    public:
        ListNode* swapPairs(ListNode* head){
            ListNode *dummy = new ListNode(-1);
            ListNode *pre = dummy;
            
            dummy->next = head;
            while(pre->next && pre->next->next){
                ListNode *t = pre->next->next;
                pre->next->next = t->next;
                t->next = pre->next;
                pre->next = t;
                pre = t->next;  
            }
            return dummy->next;
        }
};

//递归写法稍微有些复杂
class Solution{
    public:
        ListNode* swapPairs(ListNode* head){
            if(!head || !head->next) return head;
            ListNode *t = head->next;
            head->next = swapPairs(head->next->next);
            t->next = head;
            return t;
        }
};

 

Swap Nodes in Pairs

标签:const   odi   tno   style   ret   next   use   lis   values   

原文地址:https://www.cnblogs.com/hujianglang/p/11415658.html

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