Odd Even Linked List Visualizer & Step-by-Step Algorithm Solution

Group all nodes with odd indices together followed by nodes with even indices in O(1) space and O(n) time.

Category: linked-list | Difficulty: Medium

Tags: Linked List, Two Pointers, In-Place

Odd Even Linked List

head
1
2
3
4
5
100%
state
headNode(1)
Initialization
1/18
Explanation

Starting oddEvenList with 5 nodes. Nodes are grouped into odd-indexed nodes (Row 1) and even-indexed nodes (Row 2).

Source Code
1function oddEvenList(head: ListNode | null): ListNode | null {
2 if (head === null || head.next === null) return head;
3 let odd = head;
4 let even = head.next;
5 let evenHead = even;
6
7 while (even && even.next) {
8 odd.next = even.next;
9 odd = odd.next;
10 even.next = odd.next;
11 even = even.next!;
12 }
13
14 odd.next = evenHead;
15 return head;
16}