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 0
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 */
19 #endif
20 
21 #include <assert.h>
22 #define _SEARCH_PRIVATE
23 #include <search.h>
24 #include <stdlib.h>
25 
26 
27 /* delete node with given key */
28 void *
29 _DEFUN(tdelete, (vkey, vrootp, compar),
30 	const void *vkey _AND	/* key to be deleted */
31 	void      **vrootp _AND	/* address of the root of tree */
32 	int       (*compar)(const void *, const void *))
33 {
34 	node_t **rootp = (node_t **)vrootp;
35 	node_t *p, *q, *r;
36 	int  cmp;
37 
38 	if (rootp == NULL || (p = *rootp) == NULL)
39 		return NULL;
40 
41 	while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
42 		p = *rootp;
43 		rootp = (cmp < 0) ?
44 		    &(*rootp)->llink :		/* follow llink branch */
45 		    &(*rootp)->rlink;		/* follow rlink branch */
46 		if (*rootp == NULL)
47 			return NULL;		/* key not found */
48 	}
49 	r = (*rootp)->rlink;			/* D1: */
50 	if ((q = (*rootp)->llink) == NULL)	/* Left NULL? */
51 		q = r;
52 	else if (r != NULL) {			/* Right link is NULL? */
53 		if (r->llink == NULL) {		/* D2: Find successor */
54 			r->llink = q;
55 			q = r;
56 		} else {			/* D3: Find NULL link */
57 			for (q = r->llink; q->llink != NULL; q = r->llink)
58 				r = q;
59 			r->llink = q->rlink;
60 			q->llink = (*rootp)->llink;
61 			q->rlink = (*rootp)->rlink;
62 		}
63 	}
64 	free(*rootp);				/* D4: Free node */
65 	*rootp = q;				/* link parent to new node */
66 	return p;
67 }
68