Skip to content

Commit f0ac878

Browse files
committed
Add Odd-Even Linked List reordering algorithm (two-pointer approach)
1 parent 3f53861 commit f0ac878

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* Definition for singly-linked list.
3+
*/
4+
export class ListNode {
5+
/**
6+
* Creates a new ListNode.
7+
* @param {number} value - The value of the node
8+
* @param {ListNode|null} next - The reference to the next node (default is null)
9+
*/
10+
constructor(value = 0, next = null) {
11+
this.value = value;
12+
this.next = next;
13+
}
14+
}
15+
16+
/**
17+
* Groups all nodes with odd indices together followed by even indices.
18+
* @param {ListNode} head - The head of the linked list
19+
* @returns {ListNode} - The reordered linked list
20+
*/
21+
export function oddEvenLinkedList(head) {
22+
if (!head || !head.next) return head;
23+
24+
let odd = head;
25+
let even = head.next;
26+
const evenHead = even;
27+
28+
while (even && even.next) {
29+
odd.next = even.next;
30+
odd = odd.next;
31+
even.next = odd.next;
32+
even = even.next;
33+
}
34+
35+
// Link the end of odd list to the start of even list
36+
odd.next = evenHead;
37+
38+
return head;
39+
}
40+
41+
/**
42+
* Helper function to print the linked list (for testing purposes).
43+
* @param {ListNode} head - The head of the linked list
44+
*/
45+
export function printList(head) {
46+
const values = [];
47+
let current = head;
48+
while (current) {
49+
values.push(current.value);
50+
current = current.next;
51+
}
52+
console.log(values.join(" -> "));
53+
}
54+
55+
// Tiny self-check in browser/console environment
56+
if (typeof window !== "undefined")
57+
(function selfTest() {
58+
const head = new ListNode(1,
59+
new ListNode(2,
60+
new ListNode(3,
61+
new ListNode(4,
62+
new ListNode(5)
63+
)
64+
)
65+
)
66+
);
67+
68+
console.log("Original list:");
69+
printList(head);
70+
console.log("---");
71+
72+
const reordered = oddEvenLinkedList(head);
73+
console.log("Reordered (odd-even) list:");
74+
printList(reordered);
75+
console.log("---");
76+
})();

0 commit comments

Comments
 (0)