#include<stdio.h> #include<stdlib.h> unsigned int hashIndex1(const char *key, unsigned int tablesize) { unsigned int val = 0; while (*key != '') val += *key++; return val%tablesize; } unsigned int hashIndex2(const char *key, unsigned int tablesize) { return (key[0] + 27 * key[1] + 729 * key[2]) % tablesize; } unsigned int hashIndex3(const char *key, unsigned int tablesize) { unsigned int val = 0; while (*key != '') val = (val << 5) + *key++; return val%tablesize; } unsigned int hashIndex4(unsigned int key, unsigned int tablesize) { return key%tablesize; } struct ListNode{ int value; ListNode* next; }; struct HashTab{ int tablesize; ListNode** list; }; HashTab initializeTable(int tablesize) { HashTab h; h.tablesize = tablesize; h.list = (ListNode**)malloc(sizeof(ListNode*)*tablesize); for (int i = 0; i < tablesize; ++i) h.list[i] = NULL; return h; } ListNode* FindHash(HashTab h, int key) { ListNode* L = h.list[ hashIndex4(key, h.tablesize) ]; while (L&&L->value != key) L = L->next; return L; } void InsertHash(HashTab h, int key) { ListNode* p = FindHash(h, key); if (p == NULL){ ListNode* newcell = (ListNode*)malloc(sizeof(ListNode)); newcell->next = NULL; newcell->value = key; //printf("%d ", hashIndex4(key, h.tablesize)); int index = hashIndex4(key, h.tablesize); if (h.list[index] == NULL) h.list[index] = newcell; else{ newcell->next = h.list[index]; h.list[index] = newcell; } } } void printHash(HashTab h) { ListNode* tmp; for (int i = 0; i < h.tablesize; ++i){ tmp = h.list[i]; while (tmp){ printf("%d ", tmp->value); tmp = tmp->next; } printf(" "); } } int main() { int a[] = { 4, 2, 2, 0, 20, 11, 15, 18, 20, 13 }; HashTab h = initializeTable(5); for (int i = 0; i < 10; ++i) InsertHash(h, a[i]); printHash(h); }