-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList_insert_sorted_list.java
More file actions
73 lines (50 loc) · 1.4 KB
/
Copy pathLinkedList_insert_sorted_list.java
File metadata and controls
73 lines (50 loc) · 1.4 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//Hackerrank
/* Given a reference to the head of a doubly-linked list and an integer, , create a new Node object having data value and insert it into a sorted linked list. */
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
Node SortedInsert(Node head,int data) {
if(head == null) {
head = createNode(data);
return head;
}
Node current = head;
//traverse to the insertion point
while(current.next != null) {
if(current.next.data < data) {
current = current.next;
continue;
} else {
break;
}
}
insert(current, createNode(data));
return head;
}
private void insert(Node lstNode, Node newNode) {
//perfom insertion
//newNode next becomes lastNode next
newNode.next = lstNode.next;
//lastNode next becomes newNode
lstNode.next = newNode;
//newNode prev becomes lastNode
newNode.prev = lstNode;
if(newNode.next != null) {
//newNode next, prev becomes newNode
newNode.next.prev = newNode;
}
}
private Node createNode(int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
newNode.prev = null;
return newNode;
}