题目
Given a linked list, swap every two adjacent nodes and return its head. For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
解答
class Solution {
public:
ListNode
* swapPairs(ListNode
* head) {
if(head
==NULL){
return head;
}
ListNode
*dummy
=new ListNode(
-1);
dummy
->next
=head;
ListNode
*p
=dummy;
ListNode
*before
=head;
ListNode
*after
=head
->next;
while(after
!=NULL&&before
!=NULL){
ListNode
*temp
=after
->next;
p
->next
=after;
if(temp
!=NULL)
after
=temp
->next;
p
=p
->next;
p
->next
=before;
before
=temp;
p
=p
->next;
}
if(before
!=NULL){
p
->next
=before;
p
=p
->next;
}
p
->next
=NULL;
return dummy
->next;
}
};