18 int (*compare
)(const void *key1
, const void *key2
);
19 void (*destroy
)(void *data
);
20 void (*dump
)(const void *data
);
23 static struct aa_tree cep_aa_tree
;
25 static struct node
*aa_node_alloc(void *data
)
29 new = malloc(sizeof(*new));
31 fatal("Could not allocate memory");
34 new->left
= new->right
= NULL
;
40 static struct node
*skew(struct node
*node
)
44 if (!node
|| !node
->left
|| !node
->left
->right
)
47 if (node
->left
->level
== node
->level
) {
49 * Swap the pointers of horizontal left
54 node
->left
= left
->right
;
64 static struct node
*split(struct node
*node
)
68 if (!node
|| !node
->right
||
69 !node
->right
->right
|| !node
->right
->left
)
72 if (node
->level
== node
->right
->right
->level
) {
74 * We have three horizontal right links.
75 * Take the middle element, elevate it, and return
80 node
->right
= right
->left
;
91 static struct node
*__aa_insert(void *data
, struct node
*node
)
96 return aa_node_alloc(data
);
98 cmpval
= cep_aa_tree
.compare(data
, node
->data
);
100 /* move to the left */
101 node
->left
= __aa_insert(data
, node
->left
);
102 } else if (cmpval
> 0) {
103 /* move to the right */
104 node
->right
= __aa_insert(data
, node
->right
);
106 /* duplicated, just ignore it */
117 static void aa_insert(void *data
)
119 cep_aa_tree
.root
= __aa_insert(data
, cep_aa_tree
.root
);
123 static void *lookup(const void *data
, struct node
*node
)
133 cmpval
= cep_aa_tree
.compare(data
, node
->data
);
135 /* move to the left */
136 ret
= lookup(data
, node
->left
);
137 } else if (cmpval
> 0) {
138 /* move to the right */
139 ret
= lookup(data
, node
->right
);
148 static void *aa_lookup(const void *data
)
150 return lookup(data
, cep_aa_tree
.root
);
153 static void aa_init(int (*compare
)(const void *key1
, const void *key2
),
154 void (*destroy
)(void *data
),
155 void (*dump
)(const void *data
))
158 cep_aa_tree
.size
= 0;
159 cep_aa_tree
.root
= NULL
;
160 cep_aa_tree
.compare
= compare
;
161 cep_aa_tree
.destroy
= destroy
;
162 cep_aa_tree
.dump
= dump
;
165 static size_t aa_size(void)
167 return cep_aa_tree
.size
;
170 static void dump(struct node
*node
)
177 cep_aa_tree
.dump(node
->data
);
182 static void aa_dump(void)
184 dump(cep_aa_tree
.root
);
187 static void destroy(struct node
*node
)
193 destroy(node
->right
);
195 cep_aa_tree
.destroy(node
->data
);
199 static void aa_destroy(void)
201 destroy(cep_aa_tree
.root
);
204 struct module aa_module
= {
205 .mod_name
= "AA TREE",
207 .mod_destroy
= aa_destroy
,
208 .mod_insert
= aa_insert
,
209 .mod_lookup
= aa_lookup
,