-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSolution.java
43 lines (37 loc) · 1.07 KB
/
Solution.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
package Practice.DataStructures.LinkedLists.InsertingANodeIntoASortedDoublyLinkedList;
public class Solution {
/*
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;
}
private void insertNode(Node prev, Node newNode, Node next) {
prev.next = newNode;
newNode.prev = prev;
newNode.next = next;
if (next != null) next.prev = newNode;
}
Node SortedInsert(Node head, int data) {
Node newNode = new Node();
newNode.data = data;
if (head == null) return newNode;
Node prev = head;
Node current = head.next;
while (current != null) {
if (current.data > data) {
insertNode(prev, newNode, current);
return head;
} else {
prev = current;
current = current.next;
}
}
insertNode(prev, newNode, null);
return head;
}
}