#include <sys/cdefs.h>
#if 0
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: tdelete.c,v 1.2 1999/09/16 11:45:37 lukem Exp $");
#endif
#endif
__FBSDID("$FreeBSD: src/lib/libc/stdlib/tdelete.c,v 1.6 2003/01/05 02:43:18 tjr Exp $");
#define _SEARCH_PRIVATE
#include <search.h>
#include <stdlib.h>
void *
tdelete(const void * __restrict vkey, void ** __restrict vrootp,
int (*compar)(const void *, const void *))
{
node_t **rootp = (node_t **)vrootp;
node_t *p, *q, *r;
int cmp;
if (rootp == NULL || (p = *rootp) == NULL)
return NULL;
while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
p = *rootp;
rootp = (cmp < 0) ?
&(*rootp)->llink :
&(*rootp)->rlink;
if (*rootp == NULL)
return NULL;
}
r = (*rootp)->rlink;
if ((q = (*rootp)->llink) == NULL)
q = r;
else if (r != NULL) {
if (r->llink == NULL) {
r->llink = q;
q = r;
} else {
for (q = r->llink; q->llink != NULL; q = r->llink)
r = q;
r->llink = q->rlink;
q->llink = (*rootp)->llink;
q->rlink = (*rootp)->rlink;
}
}
free(*rootp);
*rootp = q;
return p;
}