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.