24. Swap Nodes in Pairs**
https://leetcode.com/problems/swap-nodes-in-pairs/
题目描述
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
C++ 实现 1
迭代版本. 引入虚拟节点 dummy
可以简化问题.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
auto prev = dummy, p = head;
// 要交换两个节点, 先要判断 ptr 以及 ptr->next 均存在,
// 之后用 tmp 记录第三个节点, 也就是下一次交换的开始.
while (p && p->next) {
auto tmp = p->next->next;
prev->next = p->next;
prev->next->next = p;
prev = prev->next->next;
p = tmp;
}
prev->next = p; // 不管最后 p 是不是为空, 使用 prev->next 指向它就可以了.
return dummy->next;
}
};
C++ 实现 2
递归版本.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next)
return head;
ListNode *dummy = new ListNode(0);
auto post = head->next->next;
dummy->next = head->next;
dummy->next->next = head;
dummy->next->next->next = swapPairs(post);
return dummy->next;
}
};