-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathll.c
More file actions
127 lines (109 loc) · 1.99 KB
/
Copy pathll.c
File metadata and controls
127 lines (109 loc) · 1.99 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
125
126
127
#include "ll.h"
linked_list* ll_init(void)
{
linked_list* ll = (linked_list*)malloc(sizeof(struct linked_list));
if (ll)
{
ll->count = 0;
ll->head = NULL;
}
return ll;
}
void ll_destroy(linked_list *ll)
{
while(ll_pop(ll));
free(ll);
}
unsigned int ll_size(const linked_list* ll)
{
return ll->count;
}
void ll_add(linked_list* ll, void* val)
{
// create the new node
list_node* n = (list_node*)malloc(sizeof(list_node));
n->val = val;
n->next = NULL;
// now insert it
if (!(ll->head))
ll->head = n;
else
{
list_node* tmp = ll->head;
while (tmp->next)
tmp = tmp->next;
tmp->next = n;
}
ll->count++;
}
void* ll_remove(linked_list* ll, const void* data, ll_cmpfunc cmp)
{
void* val;
if (!(ll->head))
return NULL;
// are we deleting the head node?
list_node* tmp = ll->head;
if (cmp(tmp->val, data) == 0)
{
ll->head = ll->head->next;
ll->count--;
val = tmp->val;
free(tmp);
return val;
}
// check the rest of the list
while (tmp->next)
{
list_node* del = tmp->next;
if (cmp(del->val, data) == 0)
{
tmp->next = del->next;
ll->count--;
val = del->val;
free(del);
return val;
}
tmp = tmp->next;
}
return NULL;
}
void* ll_pop(linked_list* ll)
{
if (!ll || !ll->head)
return NULL;
list_node* tmp = ll->head;
ll->head = ll->head->next;
ll->count--;
void *val = tmp->val;
free(tmp);
return val;
}
const list_node* ll_iter_start(const linked_list* ll)
{
return ll->head;
}
void ll_insert(linked_list* ll, list_node* here, void* val)
{
if (!here)
return;
// create the new node
list_node* n = (list_node*)malloc(sizeof(list_node));
n->val = val;
n->next = here->next;
here->next = n;
ll->count++;
}
void ll_push(linked_list* ll, void* val)
{
if (!ll)
return;
// create the new node
list_node* n = (list_node*)malloc(sizeof(list_node));
n->val = val;
if (ll->head)
n->next = ll->head;
else
n->next = NULL;
ll->head = n;
ll->count++;
}