#define HASHSIZE 32 //待存入表格數據 char *keywords[] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while" }; char keybuf[HASHSIZE][10]; static char val_flag[HASHSIZE];//標緻已佔用存儲單元 void ClearFlag() { int i; for (i = 0;i < HASHSIZE;i++) { val_flag[i] = (HASHSIZE+1);//清標緻位 } } //哈希函數,從數據中抽出某個成員用於哈希值的計算 unsigned int hash(char *s) { unsigned int hashval; int i = 0; for (hashval = 0; *s != '\0'; s++) hashval = *s + 31 * hashval; hashval = hashval % HASHSIZE; //計算下標 while ((val_flag[hashval] != (HASHSIZE+1)) && (i<32)) { i++; hashval = (hashval + i)%HASHSIZE; //衝突處理,存儲單元(下標)偏移 } if (i<HASHSIZE) { printf("\n元素下標(%d): 衝突次數: %d -- ",hashval,i); val_flag[hashval] = hashval; //表示該單元被佔用 return hashval; } return -1; } int main(void) { int i, size, pos; size = sizeof(keywords) / sizeof(keywords[0]);//計算關鍵字數量 //將數據存入哈希表 ClearFlag(); for(i = 0;i < size; i++) strcpy(keybuf[hash(keywords[i])],keywords[i]); //根據數據結構中某個成員做爲索引值,查找對應數據 ClearFlag(); for(i = 0; i < size; i++) { pos = hash(keywords[i]); printf("%-10s: %-3d\n", keybuf[pos], pos); } return 0; }