Swap Nodes in Pairs

 1 class Solution {
 2 public:
 3     ListNode* swapPairs(ListNode* head) {
 4         if(head==NULL||head->next==NULL) return head;
 5         ListNode prehead(0);
 6         prehead.next=head;
 7         ListNode *pre=&prehead,*p;
 8         while(head&&head->next)
 9         {
10             p=head->next;
11             head->next=p->next;
12            p->next=pre->next;
13            pre->next=p;
14            
15            pre=head;
16            head=head->next;
17         }
18         return prehead.next;
19     }
20 };

posted on 2015-10-17 15:18  RenewDo  阅读(124)  评论(0编辑  收藏  举报

导航