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

Swap Nodes in Pairs

时间:2014-08-02 18:16:13      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:des   blog   io   问题   div   new   amp   log   

问题:交换相邻的两个结点
分析:建立新链表每次插入ret->next后在插入ret,需要在判断下若最后只有一个结点不需要交换,注意每次交换了结点要把尾结点的下一个指向空

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if(head==NULL || head->next==NULL) return head;
        ListNode *helper=new ListNode(0);
        ListNode *ret=head;
        ListNode *cur=helper;
        while(ret  && ret->next)
        {
            ListNode *next=ret->next->next;
            cur->next=ret->next;
            cur=cur->next;
            cur->next=ret;
            cur=cur->next;
            cur->next=NULL;
            ret=next;
        }
        if(ret) cur->next=ret;
        return helper->next;
    }
};

  

Swap Nodes in Pairs,布布扣,bubuko.com

Swap Nodes in Pairs

标签:des   blog   io   问题   div   new   amp   log   

原文地址:http://www.cnblogs.com/zsboy/p/3887245.html

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