-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathList.c
155 lines (138 loc) · 2.48 KB
/
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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <stdbool.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "List.h"
typedef uint32_t u32;
list addl(u32 key, u32 val, list l)
{
list new_head = malloc(sizeof(struct node));
new_head->val = val;
new_head->key = key;
new_head->next = l;
return new_head;
}
list new_list(void)
{
list new_list = NULL;
return new_list;
}
bool is_empty(list l)
{
return l == NULL;
}
u32 head(list l)
{
assert(!is_empty(l));
return l->val;
}
list tail(list l)
{
assert(!is_empty(l));
list new_head;
list old_head = l;
new_head = old_head->next;
free(old_head);
return new_head;
}
u32 search(u32 key, list l)
{
list traverser = l;
while (traverser && traverser->key != key)
traverser = traverser->next;
return traverser ? traverser->val : 0xFFFFFFFF;
}
bool in_list(u32 key, list l)
{
list traverser = l;
while (traverser && traverser->key != key)
{
traverser = traverser->next;
}
return !(traverser == NULL);
}
unsigned int length(list l)
{
int count = 0;
list traverser = l;
while (!is_empty(traverser))
{
traverser = traverser->next;
++count;
}
return count;
}
void concat(list l1, list l2)
{
list traverser = l1;
while (traverser->next != NULL)
{
traverser = traverser->next;
}
traverser->next = l2;
}
u32 index_ith(unsigned int i, list l)
{
assert(length(l) > i);
list traverser = l;
for (unsigned int j = 0; j < i; ++j)
{
traverser = traverser->next;
}
return traverser->val;
}
void take(unsigned int i, list l)
{
assert(length(l) > i);
list traverser = l;
for (unsigned int j = 0; j < i; ++i)
{
traverser = traverser->next;
}
list prev_node;
while (!is_empty(traverser->next))
{
prev_node = traverser;
traverser = traverser->next;
free(prev_node);
}
free(traverser);
}
list drop(unsigned int i, list l)
{
assert(length(l) >= i);
list traverser = l;
list prev_node;
for (unsigned int j = 0; j < i; j++)
{
prev_node = traverser;
traverser = traverser->next;
free(prev_node);
}
return traverser;
}
list copy_list(list l)
{
if (is_empty(l))
return NULL;
list clone = malloc(sizeof(struct node));
clone->val = l->val;
clone->next = copy_list(l->next);
return clone;
}
u32 destroy_list(list l)
{
if (is_empty(l))
return 1;
list traverser = l;
list prev_node;
while (traverser)
{
prev_node = traverser;
traverser = traverser->next;
free(prev_node);
}
return 0;
}