24. Swap Nodes in Pairs
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.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
// 事先分析好需要几个临时指针变量
// 画图分析一下指针变换顺序即可
/**
* 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* dummyHead = new ListNode(0);
// 指向dummyHead的指针
ListNode* d_pCur = dummyHead;
dummyHead->next = head;
ListNode* pCur = head;
// 至少两个非空结点才swap
while (pCur && pCur->next) {
ListNode* temp = pCur->next;
ListNode* pNext = pCur->next;
pCur->next = pCur->next->next;
pNext->next = pCur;
d_pCur->next = temp;
d_pCur = d_pCur->next->next;
pCur = pCur->next;
}
return dummyHead->next;
}
};