1 /* $NetBSD: tdelete.c,v 1.3 1999/09/20 04:39:43 lukem Exp $
4 * Tree search generalized from Knuth (6.2.2) Algorithm T just like
5 * the AT&T man page says; tdelete based on Knuth's Algorithm D.
7 * Written by reading the System V Interface Definition, not the code.
9 * Totally public domain.
12 #define _SEARCH_PRIVATE
16 __CRT_ALIAS void *__tdelete
17 (const void *key, node_t **rootp, int (*compar)(const void *, const void *))
19 /* Delete node with specified "key", from tree referred to by "rootp".
21 * NOTE: node_t is defined as a structured data type, for internal use
22 * when _SEARCH_PRIVATE is enabled; for public consumption, it becomes
23 * an alias for "void", (assuming _SEARCH_PRIVATE is NOT enabled).
28 if( (rootp == NULL) || ((p = *rootp) == NULL) || (compar == NULL) )
31 while( (cmp = (*compar)(key, (*rootp)->key)) != 0 )
34 ? &(p = *rootp)->llink /* follow llink branch */
35 : &(p = *rootp)->rlink; /* follow rlink branch */
38 return NULL; /* key not found */
40 r = (*rootp)->rlink; /* D1: */
41 if( (q = (*rootp)->llink) == NULL ) /* Left NULL? */
43 else if( r != NULL ) /* Right link is NULL? */
44 { if( r->llink == NULL ) /* D2: Find successor */
48 else /* D3: Find NULL link */
50 for( q = r->llink; q->llink != NULL; q = r->llink )
53 q->llink = (*rootp)->llink;
54 q->rlink = (*rootp)->rlink;
57 free(*rootp); /* D4: Free node */
58 *rootp = q; /* link parent to new node */
63 (const void *key, void **rootp, int (*compar)(const void *, const void *))
64 { return __tdelete (key, (node_t **)(rootp), compar); }