SDE & MLE Prep

24. Swap Nodes in Pairs

Problem

Swap every two adjacent nodes of a linked list by relinking them (not by changing values), and return the head.

Example: 1→2→3→4 → 2→1→4→3; 1→2→3 → 2→1→3

With prev before each pair a → b: rewire to prev → b → a → (rest) and advance prev = a.

Complexity: O(n).

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = prev = ListNode(0, head)
        while prev.next and prev.next.next:
            a, b = prev.next, prev.next.next
            prev.next, a.next, b.next = b, b.next, a
            prev = a
        return dummy.next