當前位置:成語大全網 - 書法字典 - 哈希表的設計及其C語言實現

哈希表的設計及其C語言實現

# include & ltstdio.h & gt

# include & ltstring.h & gt

# include & ltstdlib.h & gt

const int HASH _ TABLE _ SIZE = 13;

typedef結構hash_table_pair_s {

char * key

int值;

struct hash _ table _ pair _ s * next

} hash_table_pair_t

int elf hash(const char * key)

{

無符號長整型h = 0;

無符號長g;

while(*鍵)

{

h =(h & lt;& lt4)+*鍵++;

g = h & amp0xf0000000L

如果^= g & gt;& gt24;

h & amp= ~ g;

}

返回h;

}

void hash _ table _ insert(hash _ table _ pair _ t * hash _ table,const char *key,int value)

{

int pos

hash _ table _ pair _ t * new _ pair

char * new _ str

pos = elf HASH(key)% HASH _ TABLE _ SIZE;

if(hash _ table【pos】。關鍵!= NULL)

printf(“沖突:%s和%s\n“,key,hash _ table【pos】。重點);

new _ pair =(hash _ table _ pair _ t *)malloc(sizeof(hash _ table _ pair _ t);

new _ str =(char *)malloc(sizeof(char)*(strlen(key)+1);

strcpy(new _ str,key);

新配對-& gt;key = new _ str

新配對-& gt;價值=價值;

新配對-& gt;next =哈希表【pos】。接下來;

哈希表【位置】。next = new _ pair

}

否則{

new _ str =(char *)malloc(sizeof(char)*(strlen(key)+1);

strcpy(new _ str,key);

哈希表【位置】。key = new _ str

哈希表【位置】。價值=價值;

哈希表【位置】。next = NULL

}

}

int hash _ table _ get(hash _ table _ pair _ t * hash _ table,const char *key,int *value)

{

int pos

hash_table_pair_t *p

pos = elf HASH(key)% HASH _ TABLE _ SIZE;

for(p = & amp;哈希表【pos】;p!= NULLp = p-& gt;下壹個){

如果(!strcmp(p-& gt;key,key)({

* value = p-& gt;價值;

返回0;

}

}

返回-1;

}

int main()

{

int i,狀態,值;

const char * my birds【13】= {“robin“、“sparrow“、“hawk“、“eagle“、“海鷗“、“bluejay“、“貓頭鷹“、“cardinal“、“Jakana“、“Moa“、“白鷺“、“企鵝“、“hawk“};

HASH _ TABLE _ pair _ t * HASH _ TABLE =(HASH _ TABLE _ pair _ t *)malloc(HASH _ TABLE _ SIZE * sizeof(HASH _ TABLE _ pair _ t));

for(I = 0;我& lt哈希表大小;i++) {

哈希表【I】。key = NULL

哈希表【I】。next = NULL

哈希表【I】。值= 0;

}

for(I = 0;我& ltsizeof(my birds)/sizeof(my birds【0】);i++) {

hash _ table _ insert(hash _ table,my birds【I】,I);

}

for(I = 0;我& ltsizeof(my birds)/sizeof(my birds【0】);i++) {

status = hash _ table _ get(hash _ table,my birds【I】,& amp值);

if(status = =-1 ){

printf(“未找到%s\n“,my birds【I】);

}

否則{

printf(“找到%s: %d\n“,my birds【I】,value);

}

}

返回0;

}