Swap Nodes in Pairs — In-Place Pointer Rewiring

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 217 · Swap Nodes in Pairs

Difficulty: Medium · Pattern: In-Place Pointer Manipulation

Solutions

# Python — iterative
def swapPairs(head):
    dummy = ListNode(0, head)
    prev = dummy
    while prev.next and prev.next.next:
        a, b = prev.next, prev.next.next
        prev.next = b
        a.next = b.next
        b.next = a
        prev = a
    return dummy.next

# Recursive
def swapPairsRec(head):
    if not head or not head.next: return head
    a, b = head, head.next
    a.next = swapPairsRec(b.next)
    b.next = a
    return b
// Java
public ListNode swapPairs(ListNode head) {
    ListNode dummy = new ListNode(0, head), prev = dummy;
    while (prev.next != null && prev.next.next != null) {
        ListNode a = prev.next, b = prev.next.next;
        prev.next = b; a.next = b.next; b.next = a; prev = a;
    }
    return dummy.next;
}

Complexity

  • Time: O(n)
  • Space: O(1) iterative, O(n) recursive

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro