Skip to content

24. Swap Nodes in Pairs

Summary

Solution Approach Explanation (1-minute) Time Complexity Space Complexity
Iterative Pointer Manipulation Use a dummy head node and maintain three pointers (prev, curr, next) to iteratively swap adjacent pairs. For each pair, redirect pointers to swap positions. Continue until no more pairs exist. \(O(n)\) \(O(1)\)

Example

   [0 -> 1 -> 2 -> 3 -> 4]
-> [0 -> 2 -> 1 -> 3 -> 4]
-> [0 -> 2 -> 1 -> 4 -> 3]

Implementation

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        preHead = ListNode(None, head)

        prev = preHead
        curr = head

        while curr and curr.next:
            nxt = curr.next
            aftNxt = curr.next.next

            prev.next = nxt
            curr.next = aftNxt
            nxt.next = curr

            prev = curr
            curr = aftNxt

        return preHead.next