root / proj / src / list.c @ 246
History | View | Annotate | Download (1.89 KB)
1 | 226 | up20180642 | #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 | list_node_t* (list_node_ctor)(list_node_t *p, list_node_t *n, void *val){
|
||
10 | list_node_t *ret = malloc(sizeof(list_node_t));
|
||
11 | if(ret == NULL) return NULL; |
||
12 | ret->p = p; |
||
13 | ret->n = n; |
||
14 | ret->val = val; |
||
15 | return ret;
|
||
16 | } |
||
17 | void (list_node_dtor)(list_node_t *p){
|
||
18 | free(p); |
||
19 | } |
||
20 | list_node_t* (list_node_next)(const list_node_t *p){ return p->n; } |
||
21 | list_node_t* (list_node_prev)(const list_node_t *p){ return p->p; } |
||
22 | void** (list_node_val )(list_node_t *p){ return &p->val; } |
||
23 | |||
24 | struct list{
|
||
25 | list_node_t *begin_; |
||
26 | list_node_t *end_; |
||
27 | size_t sz; |
||
28 | }; |
||
29 | list_t* (list_ctor)(void){
|
||
30 | list_t *ret = malloc(sizeof(list_t));
|
||
31 | if(ret == NULL) return NULL; |
||
32 | ret->sz = 0;
|
||
33 | ret->begin_ = NULL; ret->end_ = NULL; |
||
34 | ret->begin_ = list_node_ctor(NULL, NULL, NULL); |
||
35 | ret->end_ = list_node_ctor(NULL, NULL, NULL); |
||
36 | if(ret->begin_ == NULL || ret->end_ == NULL){ |
||
37 | list_dtor(ret); |
||
38 | return NULL; |
||
39 | } |
||
40 | ret->begin_->n = ret->end_ ; |
||
41 | ret->end_ ->p = ret->begin_; |
||
42 | return ret;
|
||
43 | } |
||
44 | int (list_dtor)(list_t *l){
|
||
45 | if(l == NULL) return 0; |
||
46 | if(list_size(l) > 0) return 1; |
||
47 | list_node_dtor(l->begin_); |
||
48 | list_node_dtor(l->end_); |
||
49 | free(l); |
||
50 | return 0; |
||
51 | } |
||
52 | list_node_t* (list_begin )( list_t *l){ return l->begin_->n; }
|
||
53 | list_node_t* (list_end )( list_t *l){ return l->end_; }
|
||
54 | size_t (list_size )(const list_t *l){ return l->sz; } |
||
55 | list_node_t* (list_insert)(list_t *l, list_node_t *position, void *val){
|
||
56 | list_node_t *node = list_node_ctor(position->p, position, val); |
||
57 | position->p->n = node; |
||
58 | position->p = node; |
||
59 | ++l->sz; |
||
60 | return node;
|
||
61 | } |
||
62 | void* (list_erase )(list_t *l, list_node_t *position){
|
||
63 | position->p->n = position->n; |
||
64 | position->n->p = position->p; |
||
65 | void *ret = position->val;
|
||
66 | list_node_dtor(position); |
||
67 | --l->sz; |
||
68 | return ret;
|
||
69 | } |