NeetCode #323LC-1721MediumLinked List
← Back to All Problems#323 · #1721 · Swapping Nodes in a Linked List(交换链表中的节点)
📌 Problem Statement & Constraints
You are given the head of a linked list and an integer
k. Swap the values of the k-th node from the beginning and the k-th node from the end, and return the head. k is 1-indexed. Constraints: 1 <= n <= 10^5, 1 <= k <= n, 0 <= Node.val <= 100.💡 Core Algorithmic Approaches
- Find the
k-th node from the front by advancingksteps from a dummy head. - Then advance a second pointer from the dummy until the first pointer reaches the end; the second pointer lands on the
k-th node from the back. - Swap the two values (the problem asks to swap values, not nodes).
- One pass after the initial
ksteps, O(1) space.
💻 Benchmark Python3 Implementation
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(k): # fast -> k-th node from the front
fast = fast.next
first = fast
while fast: # slow -> k-th node from the back
fast = fast.next
slow = slow.next
second = slow
first.val, second.val = second.val, first.val
return head⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): a single pass.
💾 Space Complexity
O(1): two pointers.
⚠️ Interview Pitfalls & Follow-ups
- Swapping the nodes instead of the values: the problem asks for a value swap, which is simpler and avoids relinking.
- Using a 1-indexed loop
range(k - 1): with the dummy head, advancingksteps lands exactly on thek-th node. - Forgetting the dummy head: the
k = 1case would need a special branch. - Assuming
k <= n / 2: the two positions may overlap whenkis the middle node, and the swap is then a no-op -- which is correct.
⚡
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
中文速览与面试要点
交换链表中的节点
给你链表的头节点 head 和一个整数 k。 交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引 )。约束:链表中节点的数目是 n;1 ≤ k ≤ n ≤ 10^5;0 ≤ Node.val ≤ 100。
核心要点
- 两次定位 + 交换值(标准解) :① 从头走 k − 1 步找到第 k 个节点 first ;② 用快慢指针找倒数第 k 个节点 second (快指针从 first 出发走到末尾,慢指针从 head 同步前进);③ 交换两者的值。
- 为什么题目只要求交换值 :题目明确说「交换节点的 值 」,因此无需真的换节点指针,代码大幅简化。
- 找倒数第 k 个的技巧 : fast 从 first 出发, second 从 head 出发,两者同步前进直到 fast.next 为 None,此时 second 即倒数第 k 个。
- 复杂度 :两次线性遍历,O(n) 时间、O(1) 空间。
常见陷阱
- 真的去交换节点指针 :题目只要求交换 值 ,交换指针需要处理大量边界(相邻节点、k 为 1 或 n 等),复杂度远高于必要。
- 找倒数第 k 个时忘记让 fast 从 first 出发 :若 fast 也从 head 出发,两者同步前进后会得到错误的节点。
- 循环条件写成 while fast :会多走一步。应为 while fast.next 。
- k 为 1 时 :first 就是 head,second 是尾节点,交换值后返回 head,正确。
参考实现
class Solution:
def swapNodes(self, head: 'ListNode', k: int) -> 'ListNode':
# ① 找正数第 k 个节点
first = head
for _ in range(k - 1):
first = first.next
# ② 快慢指针找倒数第 k 个节点
fast = first
second = head
while fast.next:
fast = fast.next
second = second.next
# ③ 交换值(题目只要求交换值)
first.val, second.val = second.val, first.val
return head