-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
76 lines (69 loc) · 1.76 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
#include <stdlib.h>
#include "alloc.h"
#include "util.h"
#include "list.h"
/* alloc for Iterator's element. */
void* list_new_element(List* list)
{
void* new_element;
if (list->constructor) {
/* appointed constructor, use it. */
new_element = list->constructor();
} else {
new_element = xalloc(list->element_size);
}
return new_element;
}
/* Iteratorの取得 */
Iterator* get_iterator(List* list)
{
/* d("get_iterator\n"); */
return list->head;
}
/* 要素を持っているか? */
int iterator_has_value(Iterator* ite)
{
/* d("iterator_has_value\n"); */
return ite != NULL;
}
/* 次の要素を取得する */
void* iterator_next(Iterator* ite)
{
/* d("iterator_next\n"); */
return ite->next;
}
/* Linked Listにオブジェクトを追加する */
void list_add(List* list, void* new_element)
{
if (list->tail == NULL) {
/* 最初の要素 */
list->tail = list->head = xalloc(sizeof(Iterator));
} else {
Iterator* old_tail = list->tail;
old_tail->next = xalloc(sizeof(Iterator));
list->tail = old_tail->next;
}
list->size++;
list->tail->element = new_element;
}
/* Linked Listを開放する */
void list_free(List* list)
{
Iterator* it = get_iterator(list);
while (1) {
Iterator* old_it = it;
if (it == NULL) break;
if (it->element != NULL) {
if (list->destructor) {
/* コンストラクタが指定されている場合はそれを利用する */
list->destructor(it->element);
} else {
xfree(it->element);
}
}
it = it->next;
xfree(old_it);
}
xfree(list);
}
/* vim: set ts=4 sw=4 sts=4 expandtab fenc=utf-8: */