Swap Nodes in Pairs Visualizer & Step-by-Step Algorithm Solution

Swap every two adjacent nodes in a linked list and return its head without modifying node values.

Category: linked-list | Difficulty: Medium

Tags: Linked List, Recursion, Pointer Manipulation

Swap Nodes in Pairs

prev
D
left
1
2
3
4
100%
state
prevDummy
leftNode(1)
rightnull
nextPairnull
Initialization
1/21
Explanation

Create dummy node pointing to the head of the list.

Source Code
1function swapPairs(head) {
2 const dummy = new ListNode(0);
3 dummy.next = head;
4 let prev = dummy;
5 let left = head;
6
7 while (left && left.next) {
8 const right = left.next;
9 const nextPair = right.next;
10
11 right.next = left;
12 left.next = nextPair;
13 prev.next = right;
14
15 prev = left;
16 left = nextPair;
17 }
18 return dummy.next;
19}