~/DHRUVUpskilling
← board/DSA/In place reversal LinkedList/dsa-in-place-reversal-linkedlist-07
Solved·27 Aug

Swap Nodes In Pair

DifficultyMedium
PatternIn place reversal LinkedList
TrackDSA
tl;dr

Given a singly linked list, swap every two adjacent nodes of the linked list. After the swap, return the head of the linked list.

full write-up

Note: Solve the problem without modifying the values in the list's nodes. In other words, only the nodes themselves can be changed.

Constraints

  • The number of nodes in the list is in the range [0, 100].
  • 0 ≤ Node.value ≤ 100

Examples

Example 1

Input: head = [9, 0, 8, 2]

Output: [0, 9, 2, 8]

Example 2

Input: head = [0, 8, 3, 1, 9, 2, 7, 0]

Output: [8, 0, 1, 3, 2, 9, 0, 7]

Solution

Manually reverse every two pairs by storing next pair information so we can connect them after reversing.


function swapPairs(head) {
    let dummy = new Node(0, head);
    let prev = dummy;
    let curr = head;

    while (curr !== null && curr.next !== null) {
        let second = curr.next;
        let nextPair = second.next;   // where the NEXT pair will begin — grab it now, before we lose it

        // Rewire this pair using nextPair instead of re-walking .next.next
        second.next = curr;
        curr.next = nextPair;
        prev.next = second;

        // Advance to the next pair
        prev = curr;
        curr = nextPair;
    }

    return dummy.next;
}