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