1 1.2 lukem /* $NetBSD: tfind.c,v 1.2 1999/09/16 11:45:37 lukem Exp $ */ 2 1.1 christos 3 1.1 christos /* 4 1.1 christos * Tree search generalized from Knuth (6.2.2) Algorithm T just like 5 1.1 christos * the AT&T man page says. 6 1.1 christos * 7 1.1 christos * The node_t structure is for internal use only, lint doesn't grok it. 8 1.1 christos * 9 1.1 christos * Written by reading the System V Interface Definition, not the code. 10 1.1 christos * 11 1.1 christos * Totally public domain. 12 1.1 christos */ 13 1.1 christos 14 1.1 christos #include <sys/cdefs.h> 15 1.1 christos #if defined(LIBC_SCCS) && !defined(lint) 16 1.2 lukem __RCSID("$NetBSD: tfind.c,v 1.2 1999/09/16 11:45:37 lukem Exp $"); 17 1.1 christos #endif /* LIBC_SCCS and not lint */ 18 1.1 christos 19 1.2 lukem #include <assert.h> 20 1.1 christos #define _SEARCH_PRIVATE 21 1.1 christos #include <stdlib.h> 22 1.1 christos #include <search.h> 23 1.1 christos 24 1.1 christos /* find a node, or return 0 */ 25 1.1 christos void * 26 1.1 christos tfind(vkey, vrootp, compar) 27 1.1 christos const void *vkey; /* key to be found */ 28 1.1 christos void **vrootp; /* address of the tree root */ 29 1.1 christos int (*compar) __P((const void *, const void *)); 30 1.1 christos { 31 1.1 christos node_t **rootp = (node_t **)vrootp; 32 1.2 lukem 33 1.2 lukem _DIAGASSERT(vkey != NULL); 34 1.2 lukem _DIAGASSERT(compar != NULL); 35 1.2 lukem #ifdef _DIAGNOSTIC 36 1.2 lukem if (vkey == NULL || compar == NULL) 37 1.2 lukem return (NULL); 38 1.2 lukem #endif 39 1.1 christos 40 1.1 christos if (rootp == NULL) 41 1.1 christos return NULL; 42 1.1 christos 43 1.1 christos while (*rootp != NULL) { /* T1: */ 44 1.1 christos int r; 45 1.1 christos 46 1.1 christos if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */ 47 1.1 christos return *rootp; /* key found */ 48 1.1 christos rootp = (r < 0) ? 49 1.1 christos &(*rootp)->llink : /* T3: follow left branch */ 50 1.1 christos &(*rootp)->rlink; /* T4: follow right branch */ 51 1.1 christos } 52 1.1 christos return NULL; 53 1.1 christos } 54