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

leetcode24:Swap Nodes in Pairs

时间:2015-04-09 11:56:25      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:leetcode   linklist   

题目:

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

分析:

使用三个指针,P1指向第一个要交换的节点,P2指向要交换的第二个节点。pre指向第一个要交换节点的前面一个节点。交换过程如下图所示:
技术分享
第一步:p2=p1->next;
第二步: p1->next=p2->next;
第三步:p2->next=p1;
第四步:

if(prev!=head)  
    prev->next=p2;  
else  
    head=p2; 

这样就完成了一次交换。
下面准备第二次交换的初始条件。
1、 更新prev:prev=p1;
2、更新第一个要交换的节点: p1=p1->next;
完整代码如下所示:

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if(NULL==head||NULL==head->next)
         return head;
        ListNode *prev=head;  
        ListNode *p1=head;  
        ListNode *p2;
        do{  
            p2=p1->next;  
            p1->next=p2->next;  
            p2->next=p1;  
            if(prev!=head)  
                prev->next=p2;  
            else  
                head=p2;  
            prev=p1;  
            p1=p1->next;  
        }while(p1!=NULL && p1->next!=NULL); 
        return head;  

    }
};

参考资料:
1:http://blog.csdn.net/jellyyin/article/details/9174859
2:https://leetcode.com/problems/swap-nodes-in-pairs/

leetcode24:Swap Nodes in Pairs

标签:leetcode   linklist   

原文地址:http://blog.csdn.net/hjxzb/article/details/44957241

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