- Ansify function definitions.
[dragonfly.git] / lib / libc / stdlib / tdelete.c
1 /*
2  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
3  * the AT&T man page says.
4  *
5  * The node_t structure is for internal use only, lint doesn't grok it.
6  *
7  * Written by reading the System V Interface Definition, not the code.
8  *
9  * Totally public domain.
10  *
11  * $NetBSD: tdelete.c,v 1.2 1999/09/16 11:45:37 lukem Exp $
12  * $FreeBSD: src/lib/libc/stdlib/tdelete.c,v 1.1.2.1 2000/08/17 07:38:39 jhb Exp $
13  * $DragonFly: src/lib/libc/stdlib/tdelete.c,v 1.4 2005/11/20 12:37:49 swildner Exp $
14  */
15
16 #include <sys/cdefs.h>
17
18 #include <assert.h>
19 #define _SEARCH_PRIVATE
20 #include <search.h>
21 #include <stdlib.h>
22
23
24 /* delete node with given key */
25 void *
26 tdelete(const void *vkey,                               /* key to be deleted */
27         void **vrootp,                                  /* address of the root of tree */
28         int (*compar)(const void *, const void *))
29 {
30         node_t **rootp = (node_t **)vrootp;
31         node_t *p, *q, *r;
32         int  cmp;
33
34         if (rootp == NULL || (p = *rootp) == NULL)
35                 return NULL;
36
37         while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
38                 p = *rootp;
39                 rootp = (cmp < 0) ?
40                     &(*rootp)->llink :          /* follow llink branch */
41                     &(*rootp)->rlink;           /* follow rlink branch */
42                 if (*rootp == NULL)
43                         return NULL;            /* key not found */
44         }
45         r = (*rootp)->rlink;                    /* D1: */
46         if ((q = (*rootp)->llink) == NULL)      /* Left NULL? */
47                 q = r;
48         else if (r != NULL) {                   /* Right link is NULL? */
49                 if (r->llink == NULL) {         /* D2: Find successor */
50                         r->llink = q;
51                         q = r;
52                 } else {                        /* D3: Find NULL link */
53                         for (q = r->llink; q->llink != NULL; q = r->llink)
54                                 r = q;
55                         r->llink = q->rlink;
56                         q->llink = (*rootp)->llink;
57                         q->rlink = (*rootp)->rlink;
58                 }
59         }
60         free(*rootp);                           /* D4: Free node */
61         *rootp = q;                             /* link parent to new node */
62         return p;
63 }