Swap Nodes in Pairs

Swap every two adjacent nodes in place using a dummy and a sliding triple.

Medium
Time O(n) Space O(1)
LeetCode
2 min read
linked-list

Problem#

Swap every two adjacent nodes (not just values). For a trailing single node, leave it as is.

Examples#

  • [1,2,3,4][2,1,4,3]
  • [1,2,3][2,1,3]

Constraints#

  • 0 <= n <= 100.

Approach#

Dummy head + a “before” pointer. Per iteration, take a = before->next, b = a->next; rewire before → b → a → b.next. Advance before to a (the new second of the pair).

Solution#

Swap Nodes in Pairs
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(0, head);
ListNode* before = &dummy;
while (before->next && before->next->next) {
ListNode *a = before->next, *b = a->next;
a->next = b->next;
b->next = a;
before->next = b;
before = a;
}
return dummy.next;
}
};

Editorial#

A special case of reverse-in-k-group with k=2, but the explicit three-line rewire is cleaner and reads more directly. The dummy makes the head swap uniform.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.