Wed, 04 Jan 2012 14:51:54 +0100
added clone and equals to lists
1 #include "dlist.h"
3 UcxDlist *ucx_dlist_clone(UcxDlist *l, copy_func fnc, void *data) {
4 UcxDlist *ret = NULL;
5 while (l != NULL) {
6 if (fnc != NULL) {
7 ret = ucx_dlist_append(ret, fnc(l->data, data));
8 } else {
9 ret = ucx_dlist_append(ret, l->data);
10 }
11 l = l->next;
12 }
13 return ret;
14 }
16 int ucx_dlist_equals(UcxDlist *l1, UcxDlist *l2, cmp_func fnc, void* data) {
17 if (l1 == l2) return 1;
19 while (l1 != NULL && l2 != NULL) {
20 if (fnc == NULL) {
21 if (l1->data != l2->data) return 0;
22 } else {
23 if (fnc(l1->data, l2->data, data) != 0) return 0;
24 }
25 l1 = l1->next;
26 l2 = l2->next;
27 }
29 return (l1 == NULL && l2 == NULL);
30 }
32 void ucx_dlist_free(UcxDlist *l) {
33 UcxDlist *e = l, *f;
34 while (e != NULL) {
35 f = e;
36 e = e->next;
37 free(f);
38 }
39 }
41 UcxDlist *ucx_dlist_append(UcxDlist *l, void *data) {
42 UcxDlist *nl = (UcxDlist*) malloc(sizeof(UcxDlist));
43 if (nl == NULL) return NULL;
45 nl->data = data;
46 nl->next = NULL;
47 if (l == NULL) {
48 return nl;
49 } else {
50 UcxDlist *t = ucx_dlist_last(l);
51 t->next = nl;
52 nl->prev = t;
53 return l;
54 }
55 }
57 UcxDlist *ucx_dlist_prepend(UcxDlist *l, void *data) {
58 UcxDlist *nl = ucx_dlist_append(NULL, data);
59 if (nl == NULL) return NULL;
61 if (l != NULL) {
62 nl->next = l;
63 l->prev = nl;
64 }
65 return nl;
66 }
68 UcxDlist *ucx_dlist_concat(UcxDlist *l1, UcxDlist *l2) {
69 if (l1 == NULL) {
70 return l2;
71 } else {
72 UcxDlist *last = ucx_dlist_last(l1);
73 last->next = l2;
74 l2->prev = last;
75 return l1;
76 }
77 }
79 UcxDlist *ucx_dlist_last(UcxDlist *l) {
80 if (l == NULL) return NULL;
82 UcxDlist *e = l;
83 while (e->next != NULL) {
84 e = e->next;
85 }
86 return e;
87 }
89 UcxDlist *ucx_dlist_get(UcxDlist *l, int index) {
90 if (l == NULL) return NULL;
92 UcxDlist *e = l;
93 while (e->next != NULL && index > 0) {
94 e = e->next;
95 index--;
96 }
98 return index == 0 ? e : NULL;
99 }
101 size_t ucx_dlist_size(UcxDlist *l) {
102 if (l == NULL) return 0;
104 UcxDlist *e = l;
105 size_t s = 1;
106 while (e->next != NULL) {
107 e = e->next;
108 s++;
109 }
111 return s;
112 }
114 void ucx_dlist_foreach(UcxDlist *l, ucx_callback fnc, void* data) {
115 UcxDlist *e = l;
116 while (e != NULL) {
117 fnc(e, data);
118 e = e->next;
119 }
120 }
122 /* dlist specific functions */
123 UcxDlist *ucx_dlist_first(UcxDlist *l) {
124 if (l == NULL) return NULL;
126 UcxDlist *e = l;
127 while (e->prev != NULL) {
128 e = e->prev;
129 }
130 return e;
131 }