-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked_list.c
94 lines (70 loc) · 1.54 KB
/
linked_list.c
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
#include <stdio.h>
#include <stdlib.h>
struct node {
int payload;
struct node *next;
};
void create_node(struct node **nodepp, int data) {
struct node *nodeptr = (struct node *)malloc(sizeof(struct node));
(*nodepp) = nodeptr;
(*nodepp)->payload = data;
(*nodepp)->next = NULL;
/* printf("New node has address %p\n", nodeptr); */
return;
}
void show_list(struct node *nptr) {
static int j = 0;
/* done */
if (!nptr)
return;
printf("Node %d at %p has payload %d\n", j, nptr, nptr->payload);
nptr = nptr->next;
j++;
show_list(nptr);
}
void add_node(struct node *newnode, struct node **tail) {
if (*tail == NULL) {
*tail = newnode;
return;
}
/* set *listp to tail */
while ((*tail)->next)
(*tail) = (*tail)->next;
/* add nptr after current tail */
(*tail)->next = newnode;
/* set new tail to nptr */
*tail = newnode;
return;
}
void freelist(struct node **list) {
struct node *head = *list, *save = *list;
/* find tail */
while ((*list)->next) {
save = *list;
(*list) = (*list)->next;
}
if (!save->next) {
printf("Freeing %p\n", save);
free(save);
return;
}
printf("Freeing %p\n", save->next);
free(save->next);
*list = save;
(*list)->next = NULL;
freelist(&head);
}
int main(void) {
int i;
struct node *newnode, *list, *HEAD = NULL;
create_node(&HEAD, 0);
list = HEAD;
for (i = 1; i < 5; i++) {
create_node(&newnode, i);
add_node(newnode, &list);
printf("\nList is:\n");
show_list(HEAD);
}
freelist(&HEAD);
exit(0);
}