dummy + prev/a/b/next 四指针每轮重连已交换段和待处理段。
OJ: leetcodecn
题目 ID: swap-nodes-in-pairs
难度:普及+/提高
标签:链表递归cpppython
日期: 2026-07-28 22:05
题意
两两交换链表中的相邻节点,返回头节点。不能只交换值。
思路
dummy 头结点下,每轮维护 prev -> a -> b -> next 四个指针,把 a 和 b 交换后接入。注意最后 prev 移动到 a 的位置,因为 a 已成为已交换段的尾节点。
代码
cpp
/**
* Author by Rainboy
*/
// main.cpp:dummy + prev/a/b/next 四指针重连。
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode dummy(0);
dummy.next = head;
auto prev = &dummy;
while (prev->next && prev->next->next) {
auto a = prev->next, b = a->next;
a->next = b->next;
b->next = a;
prev->next = b;
prev = a;
}
return dummy.next;
}
};
ListNode *build(istream &in, int n) {
if (!n)
return nullptr;
auto head = new ListNode(0), cur = head;
for (int i = 0, v; i < n; i++) {
in >> v;
cur->next = new ListNode(v);
cur = cur->next;
}
return head->next;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
auto head = build(cin, n);
head = Solution().swapPairs(head);
for (auto p = head; p; p = p->next)
cout << p->val << ' ';
return 0;
}python
#!/usr/bin/env python3
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = ListNode(0)
dummy.next = head
prev = dummy
while prev.next and prev.next.next:
a = prev.next
b = a.next
a.next = b.next
b.next = a
prev.next = b
prev = a
return dummy.next
def build(arr):
dummy = cur = ListNode(0)
for v in arr:
cur.next = ListNode(v)
cur = cur.next
return dummy.next
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
head = build(a)
head = Solution().swapPairs(head)
while head:
print(head.val, end=" ")
head = head.next
if __name__ == "__main__":
main()复杂度
- 时间复杂度:O(n)。
- 空间复杂度:O(1)。
总结
两两交换是"K 个一组翻转"的特例(k=2),掌握 k=2 的指针重连后推广到一般 k。