practical of programming 第二章 hash

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned int hash(char *str);

enum { MULTIPLIER = 31, NHASH = 131};
/* MULTIPLIER是一个计算hash值的因数,一般取31和37,
NHASH是hash表的大小,最好为素数 */

typedef struct Nameval Nameval;
struct Nameval{
char *name;
int value;
Nameval *next;   /* in chain */
};
Nameval *symtab[NHASH];  /* a symbol table */

/* lookup: find name in symtab, with optional create */
Nameval* lookup(char *name, int create, int value){
int h;
Nameval *sym;
h = hash(name);
for(sym = symtab[h];sym!=NULL;sym = sym->next){
if (strcmp(name, sym->name)==0)
return sym;
}
if (create){
sym = (Nameval *)malloc(sizeof(Nameval));
sym->name = name;  /* assumed allocate elsewhere */
sym->value = value;
sym->next = symtab[h];  /* add to the head of list */
symtab[h] = sym;
}
return sym;
}


/* hash: compute hash value of string  */
unsigned int hash(char *str){
unsigned int h;
unsigned char *p;
h = 0;
for (p = (unsigned char *)str; *p!='\0'; p++)
h = MULTIPLIER * h + *p;
return h%NHASH;
}

posted @ 2010-03-01 01:09  莫忆往西  阅读(115)  评论(0编辑  收藏  举报