-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathlist.h
126 lines (110 loc) · 2.47 KB
/
list.h
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
#ifndef MAZUCC_LIST_H
#define MAZUCC_LIST_H
#include <stdbool.h>
#include <stdlib.h>
typedef struct __ListNode {
void *elem;
struct __ListNode *next, *prev;
} ListNode;
typedef struct {
int len;
ListNode *head, *tail;
} List;
typedef struct {
ListNode *ptr;
} Iter;
#define EMPTY_LIST ((List){.len = 0, .head = NULL, .tail = NULL})
static inline List *make_list(void)
{
List *r = malloc(sizeof(List));
r->len = 0;
r->head = r->tail = NULL;
return r;
}
static inline void *make_node(void *elem)
{
ListNode *r = malloc(sizeof(ListNode));
r->elem = elem;
r->next = NULL;
r->prev = NULL;
return r;
}
static inline void list_push(List *list, void *elem)
{
ListNode *node = make_node(elem);
if (!list->head) {
list->head = node;
} else {
list->tail->next = node;
node->prev = list->tail;
}
list->tail = node;
list->len++;
}
static inline void *list_pop(List *list)
{
if (!list->head)
return NULL;
ListNode *tail = list->tail;
void *r = tail->elem;
list->tail = tail->prev;
if (list->tail)
list->tail->next = NULL;
else
list->head = NULL;
free(tail);
return r;
}
static void list_unshift(List *list, void *elem)
{
ListNode *node = make_node(elem);
node->next = list->head;
if (list->head)
list->head->prev = node;
list->head = node;
if (!list->tail)
list->tail = node;
list->len++;
}
static inline Iter list_iter(void *ptr)
{
return (Iter){
.ptr = ((List *) ptr)->head,
};
}
static inline bool iter_end(const Iter iter)
{
return !iter.ptr;
}
static inline void *iter_next(Iter *iter)
{
if (!iter->ptr)
return NULL;
void *r = iter->ptr->elem;
iter->ptr = iter->ptr->next;
return r;
}
static inline List *list_reverse(List *list)
{
List *r = make_list();
for (Iter i = list_iter(list); !iter_end(i);)
list_unshift(r, iter_next(&i));
return r;
}
static inline int list_len(List *list)
{
return list->len;
}
#define list_safe_next(node) ((node) ? (node)->next : NULL)
#define list_for_each_safe(node, tmp, list) \
for ((node) = (list)->head, (tmp) = list_safe_next(node); (node); \
(node) = (tmp), (tmp) = list_safe_next(node))
static inline void list_free(List *list)
{
ListNode *node, *tmp;
list_for_each_safe (node, tmp, list) {
free(node->elem);
free(node);
}
}
#endif /* MAZUCC_LIST_H */