-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertInASortedWayInASortedDDL.java
More file actions
49 lines (41 loc) · 1.05 KB
/
InsertInASortedWayInASortedDDL.java
File metadata and controls
49 lines (41 loc) · 1.05 KB
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
/*class of the node of the DLL is as
class Node {
int data;
Node prev, next;
Node(int item)
{data = item;
next = prev = null;
}
}
*/
// function should insert a new node in sorted way in
// a sorted doubly linked list
class GfG
{
public static Node sortedInsert(Node head, int x)
{
Node newNode = new Node(x);
Node temp;
if(head == null) {
head = newNode;
}
else if(head.data > newNode.data) {
newNode.next = head;
newNode.next.prev = newNode;
head = newNode;
}
else {
temp = head;
while(temp.next != null && temp.next.data < newNode.data) {
temp = temp.next;
}
newNode.next = temp.next;
if(newNode.next != null) {
newNode.next.prev = newNode;
}
temp.next = newNode;
newNode.prev = temp;
}
return head;
}
}