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