1
2 #include
3 #include
4
5 #include
6
7 void dlist_init(DList *list, void (*destroy)(void *data)) {
8 list->size = 0;
9 list->destroy = destroy;
10 list->head = NULL;
11 list->tail = NULL;
12 return;
13 }
14
15 void dlist_destroy(DList *list) {
16 void *data;
17 while(dlist_size(list) > 0) {
18 if(dlist_remove(list, dlist_tail(list), (void **)&data) == 0 &&
19 list->destroy != NULL) {
20 list->destroy(data);
21 }
22 }
23 memset(list, 0, sizeof(DList));
24 return;
25 }
26
27 int dlist_ins_next(DList *list, DListElmt *element, const void *data) {
28 DListElmt *new_element;
29 if(element == NULL && dlist_size(list) != 0)
30 return -1;
31 if((new_element = (DListElmt *)malloc(sizeof(DListElmt)))== NULL)
32 return -1;
33
34 new_element->data = (void *)data;
35 if(dlist_size(list) == 0) {
36 list->head = new_element;
37 list->head->prev = NULL;
38 list->head->next = NULL;
39 list->tail = new_element;
40 } else {
41 new_element->next = element->next;
42 new_element->prev = element;
43 if(element->next == NULL)
44 list->tail = new_element;
45 else
46 element->next->prev = new_element;
47 element->next = new_element;
48 }
49 list->size++;
50 return 0;
51 }
52
53 int dlist_ins_prev(DList *list, DListElmt *element, const void *data) {
54 DListElmt *new_element;
55 if(element == NULL && dlist_size(list) != 0)
56 return -1;
57 if((new_element = (DListElmt *)malloc(sizeof(DListElmt))) == NULL)
58 return -1;
59
60 new_element->data = (void *)data;
61 if(dlist_size(list) == 0) {
62 list->head = new_element;
63 list->head->prev = NULL;
64 list->head->next = NULL;
65 list->tail = new_element;
66 } else {
67 new_element->next = element;
68 new_element->prev = element->prev;
69 if(element->prev = NULL)
70 list->head = new_element;
71 else
72 element->prev->next = new_element;
73 element->prev = new_element;
74 }
75 list->size++;
76 return 0;
77 }
78
79 int dlist_remove(DList *list, DListElmt *element, void **data) {
80 if(element == NULL || dlist_size(list) == 0)
81 return -1;
82
83 *data = element->data;
84 if(element == list->head) {
85 list->head = element->next;
86 if(list->head == NULL)
87 list->tail = NULL;
88 else
89 element->next->prev = NULL;
90 } else {
91 element->prev->next = element->next;
92 if(element->next == NULL)
93 list->tail = element->prev;
94 else
95 element->next->prev = element->prev;
96 }
97 free(element);
98 list->size--;
99 return 0;
100 }
101
102