-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathInsertANodeInSortedDoublyLinkedList.java
52 lines (43 loc) Β· 1.25 KB
/
InsertANodeInSortedDoublyLinkedList.java
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
package linkedlist;
import java.util.Scanner;
public class InsertANodeInSortedDoublyLinkedList {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
DoublyLL head = new DoublyLL();
head.input();
head.print();
int data = s.nextInt();
head = insertNode(head, data);
System.out.println();
head.print();
}
private static DoublyLL insertNode(DoublyLL head, int data){
if(head == null)
return head;
if(data <= head.data){
DoublyLL node = new DoublyLL(data);
node.next = head;
head.prev = node;
return node;
}
DoublyLL temp = head.next, first = head;
while (temp != null){
if(data <= temp.data){
DoublyLL node = new DoublyLL(data);
node.next = temp;
temp.prev = node;
node.prev = first;
first.next = node;
break;
}
first = first.next;
temp = temp.next;
}
if(temp == null){
DoublyLL node = new DoublyLL(data);
node.prev = first;
first.next = node;
}
return head;
}
}