tsearch.c revision 1.1
11.1Schristos/* $NetBSD: tsearch.c,v 1.1 1999/02/22 10:33:16 christos Exp $ */ 21.1Schristos 31.1Schristos/* 41.1Schristos * Tree search generalized from Knuth (6.2.2) Algorithm T just like 51.1Schristos * the AT&T man page says. 61.1Schristos * 71.1Schristos * The node_t structure is for internal use only, lint doesn't grok it. 81.1Schristos * 91.1Schristos * Written by reading the System V Interface Definition, not the code. 101.1Schristos * 111.1Schristos * Totally public domain. 121.1Schristos */ 131.1Schristos 141.1Schristos#include <sys/cdefs.h> 151.1Schristos#if defined(LIBC_SCCS) && !defined(lint) 161.1Schristos__RCSID("$NetBSD: tsearch.c,v 1.1 1999/02/22 10:33:16 christos Exp $"); 171.1Schristos#endif /* LIBC_SCCS and not lint */ 181.1Schristos 191.1Schristos#define _SEARCH_PRIVATE 201.1Schristos#include <search.h> 211.1Schristos#include <stdlib.h> 221.1Schristos 231.1Schristos/* find or insert datum into search tree */ 241.1Schristosvoid * 251.1Schristostsearch(vkey, vrootp, compar) 261.1Schristos const void *vkey; /* key to be located */ 271.1Schristos void **vrootp; /* address of tree root */ 281.1Schristos int (*compar) __P((const void *, const void *)); 291.1Schristos{ 301.1Schristos node_t *q; 311.1Schristos node_t **rootp = (node_t **)vrootp; 321.1Schristos 331.1Schristos if (rootp == NULL) 341.1Schristos return NULL; 351.1Schristos 361.1Schristos while (*rootp != NULL) { /* Knuth's T1: */ 371.1Schristos int r; 381.1Schristos 391.1Schristos if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */ 401.1Schristos return *rootp; /* we found it! */ 411.1Schristos 421.1Schristos rootp = (r < 0) ? 431.1Schristos &(*rootp)->llink : /* T3: follow left branch */ 441.1Schristos &(*rootp)->rlink; /* T4: follow right branch */ 451.1Schristos } 461.1Schristos 471.1Schristos q = malloc(sizeof(node_t)); /* T5: key not found */ 481.1Schristos if (q != 0) { /* make new node */ 491.1Schristos *rootp = q; /* link new node to old */ 501.1Schristos q->key = (void *)vkey; /* initialize new node */ 511.1Schristos q->llink = q->rlink = NULL; 521.1Schristos } 531.1Schristos return q; 541.1Schristos} 55