一定要用好dummy节点,当head节点改变的时候,别忘了可以用dummy节点
/**
* 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) {
if(head == NULL){
return head;
}
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *prev = dummy, *cur = head;
while(cur && cur->next){
ListNode *tmp = cur->next->next;
prev->next = cur->next;
cur->next->next = cur;
cur->next = tmp;
prev = cur;
cur = tmp;
}
return dummy->next;
}
};