-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingly_linked_list.c
More file actions
124 lines (101 loc) · 1.72 KB
/
singly_linked_list.c
File metadata and controls
124 lines (101 loc) · 1.72 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
#include <stdio.h>
#include <malloc.h>
typedef struct linked_list {
int value;
struct linked_list *next;
} LL_t;
LL_t *root = (LL_t *)NULL;
int add (LL_t **head)
{
LL_t *tmp = malloc (sizeof(LL_t));
if (tmp == (LL_t *)NULL) {
printf("memory allocation failure!\n");
return 1;
}
tmp->next = NULL;
printf("Enter number :");
scanf("%d", &tmp->value);
if (*head != (LL_t *)NULL)
tmp->next = *head;
*head = tmp;
return 0;
}
void disp (LL_t *head)
{
for(; head; head = head->next)
printf("%d\n", head->value);
}
void free_list (LL_t *head)
{
LL_t *tmp;
for(; head;) {
tmp = head;
head = head->next;
free(tmp);
}
}
int free_element(LL_t **head, int value)
{
LL_t *tmp;
if ((*head)->value == value) {
tmp = *head;
*head = (*head)->next;
free(tmp);
return 0;
}
for (tmp = *head; tmp; tmp = tmp->next) {
if (tmp->next->value == value ) {
LL_t * del = tmp->next;
tmp->next = tmp->next->next;
free(del);
return 0;
}
}
return -1;
}
void rev (LL_t *head)
{
if (head->next) {
rev(head->next);
head->next->next = head;
head->next = (LL_t *) NULL;
} else {
root = head;
}
}
int main()
{
int choice;
int value, br = 1;
printf ("choice 1 for add, 2 for disp, 3 for free element, 4 for free list, 5 for reverse, 6 for exit\n");
while (br) {
printf("Enter choice :");
scanf("%d", &choice);
switch (choice) {
case 1:
if (add(&root))
goto failure;
break;
case 2:
disp(root);
break;
case 3:
printf("Enter number :");
scanf("%d", &value);
free_element(&root, value);
break;
case 4:
free_list(root);
break;
case 5:
rev(root);
break;
default:
br = 0;
break;
}
}
failure:
free_list(root);
return 0;
}