标签: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
标签:des blog io 问题 div new amp log
原文地址:http://www.cnblogs.com/zsboy/p/3887245.html