-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathLL012.java
37 lines (29 loc) · 952 Bytes
/
LL012.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
class Solution {
//Function to sort a linked list of 0s, 1s and 2s.
static Node segregate(Node head) {
if(head == null || head.next == null) return head;
Node zeroD = new Node(0);
Node oneD = new Node(0);
Node twoD = new Node(0);
Node zero=zeroD, one=oneD, two=twoD;
Node cur = head;
while(cur != null) {
if(cur.data == 0) {
zero.next = cur;
zero = zero.next;
} else if(cur.data == 1) {
one.next = cur;
one = one.next;
} else {
two.next = cur;
two = two.next;
}
cur = cur.next;
}
zero.next = (oneD.next != null) ? oneD.next : twoD.next;
one.next = twoD.next;
two.next = null;
head = zeroD.next;
return head;
}
}