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