Swap Nodes in Pairs

问题:交换相邻的两个结点
分析:建立新链表每次插入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;
    }
};

  

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