5 /* See Knuth Volume 3, 6.2.3 */
7 Avl *avllookup(Avltree*, Avl*);
8 Avl *avldelete(Avltree*, Avl*);
9 Avl *avlinsert(Avltree*, Avl*);
12 avlcreate(int (*cmp)(Avl*, Avl*))
16 t = malloc(sizeof(*t));
26 avllookup(Avltree *t, Avl *k)
47 static int insert(int (*)(Avl*, Avl*), Avl*, Avl**, Avl*, Avl**);
50 avlinsert(Avltree *t, Avl *k)
55 insert(t->cmp, nil, &t->root, k, &old);
59 static int insertfix(int, Avl**);
62 insert(int (*cmp)(Avl*, Avl*), Avl *p, Avl **qp, Avl *k, Avl **oldp)
78 c = c > 0 ? 1 : c < 0 ? -1: 0;
89 fix = insert(cmp, q, q->c + (c+1)/2, k, oldp);
91 return insertfix(c, qp);
95 static Avl *singlerot(int, Avl*);
96 static Avl *doublerot(int, Avl*);
99 insertfix(int c, Avl **t)
104 if(s->balance == 0) {
108 if(s->balance == -c) {
112 if(s->c[(c+1)/2]->balance == c)
120 static int delete(int (*cmp)(Avl*, Avl*), Avl**, Avl*, Avl**);
121 static int deletemin(Avl**, Avl**);
122 static int deletefix(int, Avl**);
125 avldelete(Avltree *t, Avl *k)
132 delete(t->cmp, &t->root, k, &old);
137 delete(int (*cmp)(Avl*, Avl*), Avl **qp, Avl *k, Avl **oldp)
147 c = c > 0 ? 1 : c < 0 ? -1: 0;
156 fix = deletemin(q->c+1, &e);
164 return deletefix(-1, qp);
167 fix = delete(cmp, q->c + (c+1)/2, k, oldp);
169 return deletefix(-c, qp);
174 deletemin(Avl **qp, Avl **oldp)
187 fix = deletemin(q->c, oldp);
189 return deletefix(1, qp);
193 static Avl *rotate(int, Avl*);
196 deletefix(int c, Avl **t)
202 if(s->balance == 0) {
206 if(s->balance == -c) {
211 if(s->c[a]->balance == 0) {
217 if(s->c[a]->balance == c)
226 singlerot(int c, Avl *s)
235 doublerot(int c, Avl *s)
242 s->c[a] = rotate(-c, s->c[a]);
247 if(p->balance == c) {
250 } else if(p->balance == -c) {
254 s->balance = r->balance = 0;
260 rotate(int c, Avl *s)
267 s->c[a] = n = r->c[a^1];
276 static Avl *walk1(int, Avl*);
299 for(q = q->c[a]; q->c[a^1] != nil; q = q->c[a^1])
303 for(p = q->p; p != nil && p->c[a] == q; p = p->p)