Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1019bed

Browse files
author
Ram swaroop
committed
insert in sorted list: improved
1 parent 1fc829b commit 1019bed

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/me/ramswaroop/linkedlists/InsertionInSortedList.java renamed to src/me/ramswaroop/linkedlists/InsertInSortedList.java

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,38 @@
1010
* @date: 6/21/15
1111
* @time: 10:20 PM
1212
*/
13-
public class InsertionInSortedList<E extends Comparable<E>> extends SingleLinkedList<E> {
13+
public class InsertInSortedList<E extends Comparable<E>> extends SingleLinkedList<E> {
1414

1515
/**
1616
* Insert an element in the sorted linked list.
1717
*
1818
* @param item
1919
*/
2020
public void insert(E item) {
21-
int index = 0;
2221
SingleLinkedNode<E> node = head;
22+
2323
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+
}
2631
node = node.next;
2732
}
28-
add(index, item);
2933
}
3034

3135
public static void main(String a[]) {
32-
InsertionInSortedList<Integer> linkedList = new InsertionInSortedList<>();
36+
InsertInSortedList<Integer> linkedList = new InsertInSortedList<>();
3337
linkedList.add(00);
3438
linkedList.add(11);
3539
linkedList.add(22);
3640
linkedList.add(33);
3741
linkedList.printList();
38-
linkedList.insert(13);
42+
linkedList.insert(-2);
43+
linkedList.insert(9);
44+
linkedList.insert(44);
3945
linkedList.printList();
4046
}
4147
}

0 commit comments

Comments
 (0)