kernel - Finish implementing PG_RAM / pipelined mmap operation
[dragonfly.git] / lib / libc / stdlib / tdelete.c
blob5597d46f0cf28cddcaa4e09f3eb1a6dce28a3000
1 /*
2 * Tree search generalized from Knuth (6.2.2) Algorithm T just like
3 * the AT&T man page says.
5 * The node_t structure is for internal use only, lint doesn't grok it.
7 * Written by reading the System V Interface Definition, not the code.
9 * Totally public domain.
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.6 2003/01/05 02:43:18 tjr Exp $
13 * $DragonFly: src/lib/libc/stdlib/tdelete.c,v 1.5 2005/11/24 17:18:30 swildner Exp $
16 #define _SEARCH_PRIVATE
17 #include <search.h>
18 #include <stdlib.h>
22 * delete node with given key
24 * vkey: key to be deleted
25 * vrootp: address of the root of the tree
26 * compar: function to carry out node comparisons
28 void *
29 tdelete(const void * __restrict vkey, void ** __restrict vrootp,
30 int (*compar)(const void *, const void *))
32 node_t **rootp = (node_t **)vrootp;
33 node_t *p, *q, *r;
34 int cmp;
36 if (rootp == NULL || (p = *rootp) == NULL)
37 return NULL;
39 while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
40 p = *rootp;
41 rootp = (cmp < 0) ?
42 &(*rootp)->llink : /* follow llink branch */
43 &(*rootp)->rlink; /* follow rlink branch */
44 if (*rootp == NULL)
45 return NULL; /* key not found */
47 r = (*rootp)->rlink; /* D1: */
48 if ((q = (*rootp)->llink) == NULL) /* Left NULL? */
49 q = r;
50 else if (r != NULL) { /* Right link is NULL? */
51 if (r->llink == NULL) { /* D2: Find successor */
52 r->llink = q;
53 q = r;
54 } else { /* D3: Find NULL link */
55 for (q = r->llink; q->llink != NULL; q = r->llink)
56 r = q;
57 r->llink = q->rlink;
58 q->llink = (*rootp)->llink;
59 q->rlink = (*rootp)->rlink;
62 free(*rootp); /* D4: Free node */
63 *rootp = q; /* link parent to new node */
64 return p;