NeetCode #330LC-24MediumLinked List
← Back to All Problems#330 · #24 · Swap Nodes in Pairs(两两交换链表中的节点)
📌 Problem Statement & Constraints
Given a linked list, swap every two adjacent nodes and return its head. You must not modify the values in the nodes, only the nodes themselves may be changed. Constraints: the number of nodes is in
[0, 100].💡 Core Algorithmic Approaches
- Process the list two nodes at a time with a
prevpointer that sits before the current pair. - For a pair
(first, second): pointfirst.nextatsecond.next,second.nextatfirst, andprev.nextatsecond. - Then move
prevtofirst, which is now the second node of the pair and the predecessor of the next pair. - The dummy head handles the first pair without a special case. A single trailing node is left untouched by the loop condition.
💻 Benchmark Python3 Implementation
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
prev = dummy
while prev.next and prev.next.next: # a full pair exists
first = prev.next
second = first.next
# rewire: prev -> second -> first -> rest
first.next = second.next
second.next = first
prev.next = second
prev = first # the new predecessor is the old first node
return dummy.next⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each pair is processed once.
💾 Space Complexity
O(1): the nodes are relinked.
⚠️ Interview Pitfalls & Follow-ups
- Swapping values instead of nodes: explicitly forbidden by the problem.
- Forgetting to advance
prev: the loop would reprocess the same pair and loop forever. - Advancing
prevtosecond:secondis now the head of the pair, so the correct predecessor of the next pair isfirst. - Not handling an odd-length list: the loop condition
prev.next and prev.next.nextleaves the trailing node alone.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Linked List Problems
中文速览与面试要点
两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。约束:链表中节点的数目在范围 [0, 100] 内;0 ≤ Node.val ≤ 100。
核心要点
- 哑结点 + 三指针迭代(标准解) :用 prev 指向「待交换两节点的前驱」,每轮交换 prev.next 与 prev.next.next 。
- 交换的四个指针动作 :设 first = prev.next 、 second = first.next ,则 first.next = second.next ; second.next = first ; prev.next = second ; prev = first (为下一轮准备)。
- 哑结点的作用 :当需要交换头两个节点时, prev 指向哑结点,统一了逻辑。
- 递归解法 : head.next = swapPairs(head.next.next); return second ,代码更短但栈深度 O(n/2)。
常见陷阱
- 指针操作的顺序搞错 :必须严格按 ①②③ 的顺序。若先执行 ③ 再执行 ①,会丢失 second.next 的原值。
- 忘记 prev = first :会导致死循环(prev 停在原位反复交换同一对)。
- 循环条件写成 while prev.next :只剩一个节点时会访问 prev.next.next 抛异常。必须同时判断两个。
- 不引入哑结点 :交换头两个节点时需要特判并更新 head。
- 递归解法在长链表上栈溢出 :Python 默认递归上限约 1000,n = 100 时安全。
参考实现
class Solution:
def swapPairs(self, head: 'ListNode') -> 'ListNode':
dummy = ListNode(0, head)
prev = dummy
while prev.next and prev.next.next: # 至少还剩两个节点
first = prev.next
second = first.next
first.next = second.next # ① first 跳过 second
second.next = first # ② second 指向 first
prev.next = second # ③ prev 指向新的第一个节点
prev = first # ④ prev 前移到下一组的前驱
return dummy.next