Sorting a Linked List of 0's, 1's, and 2's
Fri Mar 29 2024
segregate:
The strategy involves creating three dummy nodes as placeholders for the beginning of three separate lists
1class Node {
2  constructor(val) {
3    this.data = val;
4    this.next = null;
5  }
6}
7
8class LinkedList {
9  constructor() {
10    this.head = null;
11    this.tail = null;
12  }
13  addLast(val) {
14    let newNode = new Node(val);
15    if (!this.head) {
16      this.head = newNode;
17      this.tail = newNode;
18    } else {
19      this.tail.next = newNode;
20      this.tail = newNode;
21    }
22  }
23
24  segregate() {
25    let zeroL = new Node(0);
26    let zero = zeroL;
27    let oneL = new Node(0);
28    let one = oneL;
29    let twoL = new Node(0);
30    let two = twoL;
31    let current = this.head;
32
33    while (current) {
34      if (current.data === 0) {
35        zero.next = current;
36        zero = zero.next;
37      } else if (current.data === 1) {
38        one.next = current;
39        one = one.next;
40      } else {
41        two.next = current;
42        two = two.next;
43      }
44      current = current.next;
45    }
46    zero.next = oneL.next ? oneL.next : twoL.next;
47    oneL.next = twoL.next;
48    two.next = null;
49
50    this.head = zeroL.next;
51  }
52  print(head) {
53    let current = head;
54    while (current) {
55      console.log(current.data);
56      current = current.next;
57    }
58  }
59}
60
61const linkedlist = new LinkedList();
62linkedlist.addLast(1);
63linkedlist.addLast(2);
64linkedlist.addLast(2);
65linkedlist.addLast(1);
66linkedlist.addLast(2);
67linkedlist.addLast(0);
68linkedlist.addLast(2);
69linkedlist.addLast(2);
70linkedlist.print(linkedlist.head);
71linkedlist.segregate();
72console.log('After Segragation');
73linkedlist.print(linkedlist.head);
74