-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlinked-list-1.c
111 lines (95 loc) · 2.21 KB
/
linked-list-1.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// A linked list example program.
// To compile & link: gcc -g -Wall linked-list-1.c -lm
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
struct Node {
double data;
struct Node *next;
};
/*
* Create a node that holds the given data x,
* add the node to the front of the given list,
* and returns the resulting list.
*
* Returns NULL if malloc for the node fails.
*/
struct Node *prepend(struct Node *list, double x)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
if (node == NULL)
return NULL;
node->data = x;
node->next = list;
return node;
}
void print(struct Node *list)
{
struct Node *node = list;
while (node) {
printf("-> %g ", node->data);
node = node->next;
}
printf("\n");
}
/*
* Apply f(x) on each data item in the list.
*/
void apply(struct Node *list, double (*f)(double))
{
if (list) {
list->data = f(list->data);
apply(list->next, f);
}
}
/*
* Removes the first node (deallocating the memory for the node)
* and returns the rest of the list.
*
* Returns NULL if list is NULL.
*/
struct Node *remove_front(struct Node *list)
{
struct Node *rest = NULL;
if (list) {
rest = list->next;
free(list);
}
return rest;
}
/*
* Deallocates all nodes. Returns NULL.
*/
struct Node *remove_all_nodes(struct Node *list)
{
while (list) {
list = remove_front(list);
}
return list;
}
int main()
{
double a[] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };
int n = sizeof(a) / sizeof(a[0]);
// An initially empty list
struct Node *list = NULL;
int i;
for (i = 0; i < n; i++) {
list = prepend(list, a[i]);
}
// print the list, apply 2^x, and print the list again.
print(list);
apply(list, exp2);
print(list);
// remove first and print.
list = remove_front(list);
print(list);
// remove first and print one more time.
list = remove_front(list);
print(list);
// remove all nodes
list = remove_all_nodes(list);
assert(list == NULL);
return 0;
}