forked from alexprut/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
51 lines (45 loc) · 994 Bytes
/
Solution.cpp
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
/*
Insert Node in a doubly sorted linked list
After each insertion, the list should be sorted
Node is defined as
struct Node
{
int data;
Node *next;
Node *prev;
}
*/
void print(Node *head) {
while (head != NULL) {
cout << " " << head->data << " ";
head = head->next;
}
cout << "\n";
}
Node* SortedInsert(Node *head, int data)
{
Node *node = new Node();
node->data = data;
Node *current = head;
if (head == NULL) {
return node;
}
if (node->data < head->data) {
node->next = head;
head->prev = node;
return node;
}
while (current->data < node->data) {
if (current->next == NULL) {
current->next = node;
node->prev = current;
return head;
}
current = current->next;
}
node->prev = current->prev;
node->next = current;
node->prev->next = node;
current->prev = node;
return head;
}