-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist.c
89 lines (77 loc) · 1.34 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
#include "list.h"
struct list {
size_t size;
struct node {
void *item;
Node *next;
} *head;
};
List *new_list() {
List *new = malloc(sizeof(List));
new->size = 0;
new->head = NULL;
return new;
}
size_t size(List *list) {
return list->size;
}
void add_item(List *list, void *item) {
Node *new = malloc(sizeof(Node));
new->item = item;
new->next = NULL;
if(!list->head) {
list->head = new;
list->size++;
return;
}
Node *ptr = list->head;
while(ptr->next) {
ptr = ptr->next;
}
ptr->next = new;
list->size++;
}
void delete_item(List *list, void *item) {
if(!list->head) {
return;
}
Node *ptr = list->head;
while(ptr->next) {
if(ptr->next->item == item) {
free(ptr->next); //free dangling reference
ptr->next = ptr->next->next; //'skip' the deleted item
return;
}
ptr = ptr->next;
}
}
/*
* Node *i = NULL;
* List list = some list;
* while(i = next(list, i)) {
* //do something with item(i)
* }
*/
//fun fact originally called "each" because it behaves similarly
Node *next(List *list, Node *i) {
if(!i) {
i = list->head;
} else {
i = i->next;
}
return i; //will break when i->next is NULL
}
void *item(Node *i) {
return i->item;
}
void free_list(List *list) {
Node *ptr = list->head;
if(ptr){
Node *next;
while(next = ptr->next){
free(ptr);
ptr = next;
}
}
free(list);
}