Swap Nodes in Pairs - Linked List Reversal Pattern

Swap Nodes in Pairs in Java using the Linked List Reversal pattern: problem statement, approach, template, complexity, and interview tips.

Swap Nodes in Pairs

Problem Statement

Swap every two adjacent nodes of a linked list and return the head, without changing node values.

Pattern: Linked List Reversal

Reverse links in place by rewiring next pointers while keeping track of the previous and next nodes.

Use this pattern when the task is to reverse all or part of a list, reorder nodes, or work on the second half of a list.

Approach

  1. Keep prev, curr and next references.
  2. Point curr.next to prev, then advance all three references.
  3. Reconnect the reversed section to the untouched parts of the list.

Pattern Template (Java)

ListNode prev = null, curr = head;
while (curr != null) {
    ListNode next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
}
return prev;

Adapt this template to the exact rules of Swap Nodes in Pairs: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n) time and O(1) space for the iterative version.

Interview Tips

  • Use a dummy node to simplify changes at the head.
  • Draw the pointers on paper before coding partial reversals.
  • Start with a brute-force idea, state its complexity, then explain how the Linked List Reversal pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Reverse Linked List II | Next: Reverse Nodes in K Group

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.