-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortlinkedlist.java
More file actions
89 lines (74 loc) · 2 KB
/
Copy pathSortlinkedlist.java
File metadata and controls
89 lines (74 loc) · 2 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.LinkedList;
public class Sortlinkedlist {
Node head;
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public void sortList() {
if (head == null) {
return;
}
Node zeroD = new Node(0), oneD = new Node(0), twoD = new Node(0);
Node zero = zeroD, one = oneD, two = twoD;
Node current = head;
while (current != null) {
if (current.data == 0) {
zero.next = current;
zero = zero.next;
} else if (current.data == 1) {
one.next = current;
one = one.next;
} else {
two.next = current;
two = two.next;
}
current = current.next;
}
zero.next = (oneD.next != null) ? oneD.next : twoD.next;
one.next = twoD.next;
two.next = null;
head = zeroD.next;
}
public void append(int newData) {
Node newNode = new Node(newData);
if (head == null) {
head = newNode;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
Sortlinkedlist list = new Sortlinkedlist();
list.append(0);
list.append(1);
list.append(2);
list.append(1);
list.append(2);
list.append(0);
list.append(1);
System.out.println("Original List: ");
list.printList();
list.sortList();
System.out.println("Sorted List: ");
list.printList();
}
}
// time complexity -O(n)
// space complexity -O(1)