-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsingly-linked-list.cpp
81 lines (77 loc) · 1.56 KB
/
singly-linked-list.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
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
#include <iostream>
#include <ostream>
typedef struct list {
int item;
list *next;
} list;
void inserList(list **l, int x) {
list *temp = new list();
temp->item = x;
temp->next = NULL;
if (*l == NULL) {
*l = temp;
} else {
list *last_node = *l;
while (last_node->next != NULL) {
last_node = last_node->next;
}
last_node->next = temp;
}
return;
}
list *searchList(list *l, int x) {
if (l == NULL)
return NULL;
else if (l->item == x) {
return l;
} else if (l->next != NULL) {
return searchList(l->next, x);
} else {
return NULL;
}
}
list *PredecessorList(list *l, int x) {
if (l == NULL || l->next == NULL)
return NULL;
if ((l->next)->item == x) {
return l;
} else {
return PredecessorList(l->next, x);
}
return NULL;
}
void PrintList(list *l) {
while (l != NULL) {
std::cout << l->item << " ";
l = l->next;
}
std::cout << std::endl;
};
void deleteItem(list **l, int x) {
list *p;
list *pred;
p = searchList(*l, x);
if (p != NULL) {
pred = PredecessorList(*l, x);
if (pred == NULL) {
*l = p->next;
} else {
pred->next = p->next;
}
free(p);
}
}
int main() {
list *root = NULL;
inserList(&root, 1);
inserList(&root, 2);
inserList(&root, 0);
inserList(&root, 5);
inserList(&root, 14);
std::cout << "After insert option : ";
PrintList(root);
std::cout << "searching 3 in the list : " << ((searchList(root, 3) != 0) ? "Found" : "Not Found")<< std::endl;
deleteItem(&root, 5);
std::cout << "after deletion : ";
PrintList(root);
}