問題:交換相鄰的兩個結點
分析:建立新鏈表每次插入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; } };