标签:
#define TABLE_SIZE 200003
struct Node
{
char key[12], value[12];
bool flag;
Node () { flag = false; }
} table[TABLE_SIZE];
unsigned int BKDRHash(char *key)
{
unsigned int seed = 131;
unsigned int hash = 0;
while (*key)
{
hash = hash * seed + (*key++);
}
return (hash & 0x7FFFFFFF) % TABLE_SIZE;
}
int insert(char *key,char *value){
//return 1 means OVERWRITE
int pos = BKDRHash(key), m = 0,ret=0;
while (table[pos].flag ) {//has word
if(strcmp(table[pos].key, key) == 0){
ret=1;//key match,OVER_WRITE
break;
}
pos += 2 * (++m) - 1;
if (pos >= TABLE_SIZE) pos -= TABLE_SIZE;
}
if(1!=ret){//over write no need this
strcpy (table[pos].key, key);
}
strcpy (table[pos].value, value);
table[pos].flag = true;//mark that has word
return ret;
}
char* find(char* key){
int pos = BKDRHash(key), m = 0;
while (table[pos].flag) {
if (strcmp(table[pos].key, key) == 0) {
return table[pos].value;
}
else {
pos += 2 * (++m) - 1;
pos = (pos >= TABLE_SIZE ? pos - TABLE_SIZE : pos);
}
}
return NULL;
}
标签:
原文地址:http://www.cnblogs.com/sober-reflection/p/1358457bd8be9d91c59609915728d28a.html