OSDN Git Service

More rationalization of CRT_INLINE function implementations.
[mingw/mingw-org-wsl.git] / mingwrt / mingwex / tdelete.c
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 *
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(vkey != NULL);
34         _DIAGASSERT(compar != NULL);
35
36         if (rootp == NULL || (p = *rootp) == NULL)
37                 return NULL;
38
39         while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) {
40                 p = *rootp;
41                 rootp = (cmp < 0) ?
42                     &(*rootp)->llink :          /* follow llink branch */
43                     &(*rootp)->rlink;           /* follow rlink branch */
44                 if (*rootp == NULL)
45                         return NULL;            /* key not found */
46         }
47         r = (*rootp)->rlink;                    /* D1: */
48         if ((q = (*rootp)->llink) == NULL)      /* Left NULL? */
49                 q = r;
50         else if (r != NULL) {                   /* Right link is NULL? */
51                 if (r->llink == NULL) {         /* D2: Find successor */
52                         r->llink = q;
53                         q = r;
54                 } else {                        /* D3: Find NULL link */
55                         for (q = r->llink; q->llink != NULL; q = r->llink)
56                                 r = q;
57                         r->llink = q->rlink;
58                         q->llink = (*rootp)->llink;
59                         q->rlink = (*rootp)->rlink;
60                 }
61         }
62         free(*rootp);                           /* D4: Free node */
63         *rootp = q;                             /* link parent to new node */
64         return p;
65 }