forked from unicorn-engine/unicorn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
list.c
92 lines (82 loc) · 2.01 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
#include <stdlib.h>
#include "unicorn/platform.h"
#include "list.h"
// simple linked list implementation
struct list *list_new(void)
{
return calloc(1, sizeof(struct list));
}
// removed linked list nodes but does not free their content
void list_clear(struct list *list)
{
struct list_item *next, *cur = list->head;
while (cur != NULL) {
next = cur->next;
free(cur);
cur = next;
}
list->head = NULL;
list->tail = NULL;
}
// insert a new item at the begin of the list.
// returns generated linked list node, or NULL on failure
void *list_insert(struct list *list, void *data)
{
struct list_item *item = malloc(sizeof(struct list_item));
if (item == NULL) {
return NULL;
}
item->data = data;
item->next = list->head;
if (list->tail == NULL) {
list->tail = item;
}
list->head = item;
return item;
}
// append a new item at the end of the list.
// returns generated linked list node, or NULL on failure
void *list_append(struct list *list, void *data)
{
struct list_item *item = malloc(sizeof(struct list_item));
if (item == NULL) {
return NULL;
}
item->next = NULL;
item->data = data;
if (list->head == NULL) {
list->head = item;
} else {
list->tail->next = item;
}
list->tail = item;
return item;
}
// returns true if entry was removed, false otherwise
bool list_remove(struct list *list, void *data)
{
struct list_item *next, *cur, *prev = NULL;
// is list empty?
if (list->head == NULL) {
return false;
}
cur = list->head;
while (cur != NULL) {
next = cur->next;
if (cur->data == data) {
if (cur == list->head) {
list->head = next;
} else {
prev->next = next;
}
if (cur == list->tail) {
list->tail = prev;
}
free(cur);
return true;
}
prev = cur;
cur = next;
}
return false;
}