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++ 实现 0
(20210402 更新) 迭代版本. 引入虚拟节点, 每次都需要判断 p->next
以及 p->next->next
是否均存在.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
auto p = dummy;
while (p->next && p->next->next) {
auto a = p->next, b = p->next->next;
auto post = b->next;
p->next = b;
b->next = a;
a->next = post;
p = a;
}
return dummy->next;
}
};
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
20210402 更新. 递归版本; 代码很简洁, C++ 实现 3
写复杂了…, 忍不住更新一下.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
auto post = head->next->next;
auto p = head, q = head->next;
q->next = p;
p->next = swapPairs(post);
return q;
}
};
C++ 实现 3
递归版本.
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;
}
};