1 /* $NetBSD: tdelete.c,v 1.2 1999/09/16 11:45:37 lukem Exp $ */
2 /* $FreeBSD: src/lib/libc/stdlib/tdelete.c,v 1.1.2.1 2000/08/17 07:38:39 jhb Exp $ */
5 * Tree search generalized from Knuth (6.2.2) Algorithm T just like
6 * the AT&T man page says.
8 * The node_t structure is for internal use only, lint doesn't grok it.
10 * Written by reading the System V Interface Definition, not the code.
12 * Totally public domain.
15 #include <sys/cdefs.h>
16 #if defined(LIBC_SCCS) && !defined(lint)
17 __RCSID("$NetBSD: tdelete.c,v 1.2 1999/09/16 11:45:37 lukem Exp $");
18 #endif /* LIBC_SCCS and not lint */
21 #define _SEARCH_PRIVATE
26 /* delete node with given key */
28 tdelete(vkey, vrootp, compar)
29 const void *vkey; /* key to be deleted */
30 void **vrootp; /* address of the root of tree */
31 int (*compar) __P((const void *, const void *));
33 node_t **rootp = (node_t **)vrootp;
37 if (rootp == NULL || (p = *rootp) == NULL)
40 while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
43 &(*rootp)->llink : /* follow llink branch */
44 &(*rootp)->rlink; /* follow rlink branch */
46 return NULL; /* key not found */
48 r = (*rootp)->rlink; /* D1: */
49 if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
51 else if (r != NULL) { /* Right link is NULL? */
52 if (r->llink == NULL) { /* D2: Find successor */
55 } else { /* D3: Find NULL link */
56 for (q = r->llink; q->llink != NULL; q = r->llink)
59 q->llink = (*rootp)->llink;
60 q->rlink = (*rootp)->rlink;
63 free(*rootp); /* D4: Free node */
64 *rootp = q; /* link parent to new node */