root / proj / libs / classes / src / list.c @ 284
History | View | Annotate | Download (2.2 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 |
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 |
int (list_empty )(const list_t *l){ return !(l->sz); } |
56 |
list_node_t* (list_insert)(list_t *l, list_node_t *position, void *val){
|
57 |
list_node_t *node = list_node_ctor(position->p, position, val); |
58 |
position->p->n = node; |
59 |
position->p = node; |
60 |
++l->sz; |
61 |
return node;
|
62 |
} |
63 |
void* (list_erase )(list_t *l, list_node_t *position){
|
64 |
position->p->n = position->n; |
65 |
position->n->p = position->p; |
66 |
void *ret = position->val;
|
67 |
list_node_dtor(position); |
68 |
--l->sz; |
69 |
return ret;
|
70 |
} |
71 |
void (list_push_back)(list_t *l, void *val){ |
72 |
list_insert(l, list_end(l), val); |
73 |
} |
74 |
void** (list_front)(list_t *l){
|
75 |
return list_node_val(list_begin(l));
|
76 |
} |
77 |
void (list_pop_front)(list_t *l){
|
78 |
list_erase(l, list_begin(l)); |
79 |
} |