1 /* 2 * Tree search generalized from Knuth (6.2.2) Algorithm T just like 3 * the AT&T man page says. 4 * 5 * The node_t structure is for internal use only, lint doesn't grok it. 6 * 7 * Written by reading the System V Interface Definition, not the code. 8 * 9 * Totally public domain. 10 * 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.1.2.1 2000/08/17 07:38:39 jhb Exp $ 13 * $DragonFly: src/lib/libc/stdlib/tdelete.c,v 1.5 2005/11/24 17:18:30 swildner Exp $ 14 */ 15 16 #include <sys/cdefs.h> 17 18 #include <assert.h> 19 #define _SEARCH_PRIVATE 20 #include <search.h> 21 #include <stdlib.h> 22 23 24 /* 25 * delete node with given key 26 * 27 * Parameters: 28 * vkey: key to be deleted 29 * vrootp: address of the root of tree 30 */ 31 void * 32 tdelete(const void *vkey, void **vrootp, 33 int (*compar)(const void *, const void *)) 34 { 35 node_t **rootp = (node_t **)vrootp; 36 node_t *p, *q, *r; 37 int cmp; 38 39 if (rootp == NULL || (p = *rootp) == NULL) 40 return NULL; 41 42 while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) { 43 p = *rootp; 44 rootp = (cmp < 0) ? 45 &(*rootp)->llink : /* follow llink branch */ 46 &(*rootp)->rlink; /* follow rlink branch */ 47 if (*rootp == NULL) 48 return NULL; /* key not found */ 49 } 50 r = (*rootp)->rlink; /* D1: */ 51 if ((q = (*rootp)->llink) == NULL) /* Left NULL? */ 52 q = r; 53 else if (r != NULL) { /* Right link is NULL? */ 54 if (r->llink == NULL) { /* D2: Find successor */ 55 r->llink = q; 56 q = r; 57 } else { /* D3: Find NULL link */ 58 for (q = r->llink; q->llink != NULL; q = r->llink) 59 r = q; 60 r->llink = q->rlink; 61 q->llink = (*rootp)->llink; 62 q->rlink = (*rootp)->rlink; 63 } 64 } 65 free(*rootp); /* D4: Free node */ 66 *rootp = q; /* link parent to new node */ 67 return p; 68 } 69