]> mj.ucw.cz Git - umpf.git/blob - lists.c
fix many little bugs, release 0.1
[umpf.git] / lists.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "lists.h"
4
5 void
6 list_init(struct list* l)
7 {
8         l->head.next=&l->head;
9         l->head.prev=&l->head;
10 }
11
12 int
13 list_is_empty(struct list* l)
14 {
15         return (&l->head==l->head.next);
16 }
17
18 /* return first element of the list or NULL if empty */
19 void*
20 list_first(struct list* l)
21 {
22         return (&l->head!=l->head.next?l->head.next:NULL);      
23 }
24
25 void*
26 list_last(struct list* l)
27 {
28         return (&l->head!=l->head.prev?l->head.prev:NULL);      
29 }
30
31 void*
32 list_prev(struct list* l, struct node* n)
33 {
34         return (n->prev!=&l->head?n->prev:NULL);
35 }
36
37 void*
38 list_next(struct list* l, struct node* n)
39 {
40         return (n->next!=&l->head?n->next:NULL);
41 }
42
43 void
44 list_add_first(struct list* l, struct node* new)
45 {
46         new->prev=&l->head;
47         new->next=l->head.next;
48         l->head.next->prev=new;
49         l->head.next=new;
50 }
51
52 void
53 list_add_last(struct list* l, struct node* new)
54 {
55         new->prev=l->head.prev;
56         new->next=&l->head;
57         l->head.prev->next=new;
58         l->head.prev=new;
59 }
60
61 void
62 list_add_after(struct node* orig, struct node* new)
63 {
64         new->prev=orig;
65         new->next=orig->next;
66         orig->next->prev=new;
67         orig->next=new;
68 }
69
70 void
71 list_add_before(struct node* orig, struct node* new)
72 {
73         new->prev=orig->prev;
74         new->next=orig;
75         orig->prev->next=new;
76         orig->prev=new;
77 }
78
79 void
80 list_del_node(struct node* n)
81 {
82         n->prev->next=n->next;
83         n->next->prev=n->prev;
84         n->prev=n->next=NULL;
85 }
86
87 void*
88 list_del_first(struct list* l)
89 {
90         struct node* del;
91
92         if (list_is_empty(l)) 
93                 return NULL;
94
95         del=l->head.next;
96         list_del_node(del);
97         
98         return del;
99 }
100
101 void*
102 list_del_last(struct list* l)
103 {
104         struct node* del;
105
106         if (list_is_empty(l)) 
107                 return NULL;
108
109         del=l->head.prev;
110         list_del_node(del);
111         
112         return del;
113 }
114
115 void
116 list_cat(struct list* dst, struct list* src) 
117 {
118         struct node* dst_last = dst->head.prev;
119         struct node* src_first = src->head.next;
120         struct node* src_last = src->head.prev;
121
122         dst_last->next = src_first;
123         src_first->prev = dst_last;
124         src_last->next = &dst->head;
125         dst->head.prev = src_last;
126 }