File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ package me .ramswaroop .linkedlists ;
2+
3+ import me .ramswaroop .common .SingleLinkedList ;
4+ import me .ramswaroop .common .SingleLinkedNode ;
5+
6+ /**
7+ * Created by IntelliJ IDEA.
8+ *
9+ * @author: ramswaroop
10+ * @date: 7/5/15
11+ * @time: 1:47 PM
12+ */
13+ public class SortLinkedListOf0s1s2s {
14+
15+ /**
16+ * Sorts {@param list} consisting of only 0s, 1s and 2s as their node values.
17+ * <p/>
18+ * Time complexity: O(n)
19+ * Space complexity: O(1)
20+ *
21+ * @param list
22+ */
23+ public static void sort (SingleLinkedList <Integer > list ) {
24+ int [] count = new int [3 ];
25+ SingleLinkedNode <Integer > curr = list .head ;
26+
27+ // keep count of 0s, 1s and 2s
28+ while (curr != null ) {
29+ count [curr .item ]++;
30+ curr = curr .next ;
31+ }
32+
33+ // make a linked list of that many 0s, 1s and 2s
34+ list .clear ();
35+ for (int i = 0 ; i < count .length ; i ++) {
36+ for (int j = 0 ; j < count [i ]; j ++) {
37+ list .add (i );
38+ }
39+ }
40+ }
41+
42+ public static void main (String a []) {
43+ SingleLinkedList <Integer > linkedList = new SingleLinkedList <>();
44+ linkedList .add (0 );
45+ linkedList .add (1 );
46+ linkedList .add (2 );
47+ linkedList .add (0 );
48+ linkedList .add (1 );
49+ linkedList .add (2 );
50+ linkedList .add (1 );
51+ linkedList .printList ();
52+ sort (linkedList );
53+ linkedList .printList ();
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments