-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathZeroOneTwo.java
46 lines (43 loc) · 1.26 KB
/
ZeroOneTwo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*https://practice.geeksforgeeks.org/problems/given-a-linked-list-of-0s-1s-and-2s-sort-it/1*/
class Solution
{
//Function to sort a linked list of 0s, 1s and 2s.
static Node segregate(Node head)
{
Node zeroHead = new Node(0);
Node zeroTail = zeroHead;
Node oneHead = new Node(0);
Node oneTail = oneHead;
Node twoHead = new Node(0);
Node twoTail = twoHead;
//keep moving the head
while (head != null)
{
//keep adding new nodes to the respective lists
if (head.data == 0)
{
zeroTail.next = new Node(0);
zeroTail = zeroTail.next;
}
else if (head.data == 1)
{
oneTail.next = new Node(1);
oneTail = oneTail.next;
}
else
{
twoTail.next = new Node(2);
twoTail = twoTail.next;
}
head = head.next;
}
//attach the lists and return
if (oneHead.next != null) {
zeroTail.next = oneHead.next;
oneTail.next = twoHead.next;
return zeroHead.next;
}
zeroTail.next = twoHead.next;
return zeroHead.next;
}
}