-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist_Insertion_Sorted_Manner
More file actions
39 lines (35 loc) · 1.04 KB
/
list_Insertion_Sorted_Manner
File metadata and controls
39 lines (35 loc) · 1.04 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
void insert(const T& val) {
node<T>* ptr;
ptr = new node<T>;
ptr->val = val;
if (this->H == nullptr) { // If the list is empty
this->H = ptr;
ptr->next = ptr->prev = nullptr;
return;
}
node<T>* t = this->H; // Current node
node<T>* pr = nullptr; // Previous node (initially null)
while (t != nullptr) {
if (val < t->val) {
if (t->prev != nullptr) { // If t is not the first node
node<T>* f = t->prev;
ptr->next = t;
t->prev = ptr;
ptr->prev = f;
f->next = ptr;
} else { // If t is the first node
t->prev = ptr;
ptr->next = t;
ptr->prev = nullptr;
this->H = ptr; // Update head pointer
}
return;
}
pr = t; // Update previous node
t = t->next; // Move to the next node
}
// Insert at the end of the list
pr->next = ptr;
ptr->prev = pr;
ptr->next = nullptr;
}