-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.c
More file actions
61 lines (54 loc) · 802 Bytes
/
list.c
File metadata and controls
61 lines (54 loc) · 802 Bytes
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
// Attribution: taken from lecture notes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
list*
cons(char* xx, list* xs)
{
list* ys = malloc(sizeof(list));
ys->head = strdup(xx);
ys->tail = xs;
return ys;
}
void
free_list(list* xs)
{
if (xs) {
free_list(xs->tail);
free(xs->head);
free(xs);
}
}
void
print_list(list* xs)
{
for (; xs; xs = xs->tail) {
puts(xs->head);
}
}
long
length(list* xs)
{
long yy = 0;
for (; xs; xs = xs->tail) {
yy++;
}
return yy;
}
list*
reverse(list* xs)
{
list* ys = 0;
for (; xs; xs = xs->tail) {
ys = cons(xs->head, ys);
}
return ys;
}
list*
rev_free(list* xs)
{
list* ys = reverse(xs);
free_list(xs);
return ys;
}