Skip to content

Commit b179033

Browse files
Implemented insert node into sorted List
1 parent 62ae469 commit b179033

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.java4u.ds.linkedlist.insertNodeintoSortedList;
2+
3+
import com.java4u.ds.linkedlist.Node;
4+
5+
public class InsertNodeInSortedList {
6+
public Node insertNodeInSortedList(Node head, Node newNode) {
7+
Node current = head;
8+
if (head == null) {
9+
return newNode;
10+
}
11+
Node temp = null;
12+
while (current != null && current.getData() < newNode.getData()) {
13+
temp = current;
14+
current = current.getNext();
15+
}
16+
newNode.setNext(current);
17+
temp.setNext(newNode);
18+
return head;
19+
}
20+
21+
private static void print(Node head) {
22+
if (head == null) {
23+
return;
24+
}
25+
System.out.print(head.getData() + " ");
26+
print(head.getNext());
27+
}
28+
29+
public static void main(String[] args) {
30+
Node head = new Node(1);
31+
Node n1 = new Node(2);
32+
Node n2 = new Node(3);
33+
Node n3 = new Node(4);
34+
Node n4 = new Node(6);
35+
Node n5 = new Node(7);
36+
head.setNext(n1);
37+
n1.setNext(n2);
38+
n2.setNext(n3);
39+
n3.setNext(n4);
40+
n4.setNext(n5);
41+
System.out.println("Before Insertion of Node :");
42+
print(head);
43+
System.out.println();
44+
Node node = new Node(5);
45+
new InsertNodeInSortedList().insertNodeInSortedList(head, node);
46+
System.out.println("After Insertion of Node :");
47+
print(head);
48+
System.out.println();
49+
}
50+
51+
}

0 commit comments

Comments
 (0)