-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathascend_list.cpp
More file actions
129 lines (104 loc) · 2.27 KB
/
ascend_list.cpp
File metadata and controls
129 lines (104 loc) · 2.27 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <cstdio>
struct list_node {
int value;
list_node* next;
};
list_node* insert(list_node* root, int value) {
// new a node
list_node* node = new list_node();
if (!node) {
return root; // return root in case it's updated
}
node->value = value;
node->next = NULL;
// assume it's ascending
list_node* p = root, *prev = NULL;
while (p && p->value < value) {
prev = p;
p = p->next;
}
if (p) { // and p->value >= value
if (p == root) {
node->next = root;
root = node;
} else {
node->next = p;
prev->next = node;
}
} else { // p is null, and append to last
prev->next = node;
}
return root;
}
list_node* del(list_node* root, int value) {
list_node* p = root, *prev = NULL;
while (p && p->value != value) {
prev = p;
p = p->next;
}
if (p) { // found
if (p == root) {
p = p->next;
delete root; // safe to delete NULL??
root = p;
} else if (prev) { // for safe!!
prev->next = p->next;
delete p;
}
} else {
// not found, and do nothing
}
return root;
}
void clear(list_node* root) {
list_node* node = root;
while (node) {
list_node* next = node->next;
delete node;
node = next;
}
}
void print(list_node* root) {
list_node* node = root;
while (node) {
printf("%d\t", node->value);
node = node->next;
}
printf("\n");
}
list_node* init() {
list_node* node = new list_node();
if (!node) { // !!!check if it's null
return NULL;
}
node->value = 10;
node->next = NULL;
return node;
}
int main(int, char**) {
list_node* root = init(); // root->value is 10
if (root) {
root = insert(root, 13);
print(root);
root = insert(root, 18); // append to last
print(root);
root = insert(root, 15); // insert middle
print(root);
root = insert(root, 8); // insert before root
print(root);
root = del(root, 8); // del root
print(root);
root = del(root, 15); // del mid
print(root);
root = del(root, 18); // del last node
print(root);
root = del(root, 25); // del non-existing
print(root);
root = del(root, 10);
root = del(root, 13); // it's now empty list
print(root);
clear(root);
print(root);
}
return 0;
}