源码+注释
#include <malloc.h>
#include <stdio.h>
#define HASHSIZE 60
#define NULLKEY 0
typedef struct {
int *elem;
int count;
} HashTable;
int InitHashTable(HashTable *table);
int Hash(int key);
void InsertHash(HashTable *table, int key);
char *SearchHash(HashTable table, int key, int *add);
void PrintHashTable(HashTable table);
int main() {
HashTable table;
InitHashTable(&table);
for (int i = 50; i > 0; i--) {
InsertHash(&table, (i + 1));
}
PrintHashTable(table);
int index = 8;
int key = 5;
char *result = SearchHash(table, key, &index);
printf("%s", result);
return 0;
}
int InitHashTable(HashTable *table) {
table->count = HASHSIZE;
table->elem = (int *) malloc(sizeof(int) * HASHSIZE);
if (!table->elem) {
return -1;
}
for (int i = 0; i < HASHSIZE; i++) {
table->elem[i] = NULLKEY;
}
return 0;
}
int Hash(int key) {
for (int i = HASHSIZE; i > 0; i--) {
int j = 2;
for (; j <= i; j++) {
if (i % j == 0) {
break;
}
}
if (i == j) {
return key % i;
}
}
return -999;
}
void InsertHash(HashTable *table, int key) {
int add;
add = Hash(key);
while (table->elem[add] != NULLKEY) {
add = (add + 1) % HASHSIZE;
}
table->elem[add] = key;
}
char *SearchHash(HashTable table, int key, int *add) {
int count = 0;
while (table.elem[*add] != key) {
count++;
printf("冲突第 %d 次\n", count);
*add = (*add + 1) % HASHSIZE;
if (table.elem[*add] == NULLKEY || *add == Hash(key)) {
return "没找到";
}
}
return "找到了";
}
void PrintHashTable(HashTable table) {
printf("========= 哈希表 =========\n");
for (int i = 0; i < table.count; i++) {
printf("%d ", table.elem[i]);
}
printf("\n");
}