root / proj / libs / classes / src / list.c @ 316
History | View | Annotate | Download (2.46 KB)
1 |
#include <lcom/lcf.h> |
---|---|
2 |
|
3 |
#include "list.h" |
4 |
|
5 |
struct list_node{
|
6 |
list_node_t *p, *n; |
7 |
void *val;
|
8 |
}; |
9 |
|
10 |
list_node_t* (list_node_ctor)(list_node_t *p, list_node_t *n, void *val){
|
11 |
list_node_t *ret = malloc(sizeof(list_node_t));
|
12 |
if(ret == NULL) return NULL; |
13 |
ret->p = p; |
14 |
ret->n = n; |
15 |
ret->val = val; |
16 |
return ret;
|
17 |
} |
18 |
void (list_node_dtor)(list_node_t *p){
|
19 |
free(p); |
20 |
} |
21 |
list_node_t* (list_node_next)(const list_node_t *p){ return p->n; } |
22 |
list_node_t* (list_node_prev)(const list_node_t *p){ return p->p; } |
23 |
void** (list_node_val )(list_node_t *p){ return &p->val; } |
24 |
|
25 |
struct list{
|
26 |
list_node_t *begin_; |
27 |
list_node_t *end_; |
28 |
size_t sz; |
29 |
}; |
30 |
|
31 |
list_t* (list_ctor) (void){
|
32 |
list_t *ret = malloc(sizeof(list_t));
|
33 |
if(ret == NULL) return NULL; |
34 |
ret->sz = 0;
|
35 |
ret->begin_ = NULL; ret->end_ = NULL; |
36 |
ret->begin_ = list_node_ctor(NULL, NULL, NULL); |
37 |
ret->end_ = list_node_ctor(NULL, NULL, NULL); |
38 |
if(ret->begin_ == NULL || ret->end_ == NULL){ |
39 |
list_dtor(ret); |
40 |
return NULL; |
41 |
} |
42 |
ret->begin_->n = ret->end_ ; |
43 |
ret->end_ ->p = ret->begin_; |
44 |
return ret;
|
45 |
} |
46 |
int (list_dtor) (list_t *l){
|
47 |
if(l == NULL) return 0; |
48 |
if(list_size(l) > 0) return 1; |
49 |
list_node_dtor(l->begin_); |
50 |
list_node_dtor(l->end_); |
51 |
free(l); |
52 |
return 0; |
53 |
} |
54 |
list_node_t* (list_begin) (list_t *l){ return l->begin_->n; }
|
55 |
list_node_t* (list_end) (list_t *l){ return l->end_; }
|
56 |
size_t (list_size) (const list_t *l){ return l->sz; } |
57 |
int (list_empty) (const list_t *l){ return (l->sz ? true : false); } |
58 |
list_node_t* (list_insert) (list_t *l, list_node_t *position, void *val){
|
59 |
list_node_t *node = list_node_ctor(position->p, position, val); |
60 |
position->p->n = node; |
61 |
position->p = node; |
62 |
++l->sz; |
63 |
return node;
|
64 |
} |
65 |
void* (list_erase) (list_t *l, list_node_t *position){
|
66 |
position->p->n = position->n; |
67 |
position->n->p = position->p; |
68 |
void *ret = position->val;
|
69 |
list_node_dtor(position); |
70 |
--l->sz; |
71 |
return ret;
|
72 |
} |
73 |
void (list_push_back)(list_t *l, void *val){ |
74 |
list_insert(l, list_end(l), val); |
75 |
} |
76 |
void** (list_front) (list_t *l){
|
77 |
return list_node_val(list_begin(l));
|
78 |
} |
79 |
void (list_pop_front)(list_t *l){
|
80 |
list_erase(l, list_begin(l)); |
81 |
} |
82 |
list_node_t* (list_find) (list_t *l, void *val){
|
83 |
list_node_t *it = list_begin(l); |
84 |
while(it != list_end(l) && *list_node_val(it) != val){
|
85 |
it = list_node_next(it); |
86 |
} |
87 |
return it;
|
88 |
} |