交换相邻两个节点的顺序,不能只是改变节点的值。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* temp;
ListNode* first;
ListNode* yy;
ListNode* xx;
ListNode *cnt=new ListNode(0);
cnt->next=head;
temp=head;
first=cnt;
while(temp&&temp->next){
xx=temp->next;
yy=temp->next->next;
temp->next->next=temp;
temp->next=yy;
first->next=xx;
first=temp;
temp=temp->next;
}
return cnt->next;
}
};