File tree Expand file tree Collapse file tree 1 file changed +13
-7
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +13
-7
lines changed Original file line number Diff line number Diff line change 10
10
* @date: 6/21/15
11
11
* @time: 10:20 PM
12
12
*/
13
- public class InsertionInSortedList <E extends Comparable <E >> extends SingleLinkedList <E > {
13
+ public class InsertInSortedList <E extends Comparable <E >> extends SingleLinkedList <E > {
14
14
15
15
/**
16
16
* Insert an element in the sorted linked list.
17
17
*
18
18
* @param item
19
19
*/
20
20
public void insert (E item ) {
21
- int index = 0 ;
22
21
SingleLinkedNode <E > node = head ;
22
+
23
23
while (node != null ) {
24
- if (item .compareTo (node .item ) < 0 ) break ;
25
- index ++;
24
+ if (node .item .compareTo (item ) > 0 ) { // new node is to be inserted before head
25
+ head = new SingleLinkedNode <>(item , node );
26
+ return ;
27
+ } else if (node .next == null || node .next .item .compareTo (item ) > 0 ) { // new node to be inserted anywhere else
28
+ node .next = new SingleLinkedNode <>(item , node .next );
29
+ return ;
30
+ }
26
31
node = node .next ;
27
32
}
28
- add (index , item );
29
33
}
30
34
31
35
public static void main (String a []) {
32
- InsertionInSortedList <Integer > linkedList = new InsertionInSortedList <>();
36
+ InsertInSortedList <Integer > linkedList = new InsertInSortedList <>();
33
37
linkedList .add (00 );
34
38
linkedList .add (11 );
35
39
linkedList .add (22 );
36
40
linkedList .add (33 );
37
41
linkedList .printList ();
38
- linkedList .insert (13 );
42
+ linkedList .insert (-2 );
43
+ linkedList .insert (9 );
44
+ linkedList .insert (44 );
39
45
linkedList .printList ();
40
46
}
41
47
}
You can’t perform that action at this time.
0 commit comments