两两交换链表中的节点

24. Swap Nodes in Pairs

这里应当注意奇数个节点的时候。

 1     ListNode* swapPairs(ListNode* head) {
 2         if(!head || !head->next) return head;
 3         ListNode *p=head,*q=head->next,*k=head;
 4         while(q) {
 5             p->next=q->next;
 6             q->next=p;
 7             if(p!=head)  k->next=q;
 8             if(p==head)  head=q;
 9             k=p;
10             p=p->next;
11             if(p) q=p->next;
12             else  q=NULL;
13         }
14         return head;
15     }

 

 

posted @ 2016-09-12 21:28  胖子到瘦子  阅读(770)  评论(0编辑  收藏  举报