代码
#include<stdio.h>
#include<malloc.h>
#define TABLE_SIZE 19
typedef struct Node {
int key;
char value;
}Node,*NodePtr;
typedef struct HashList {
int length;
NodePtr elements;
}HashList,*ListPtr;
ListPtr initList(int* paraKeys, char* paraValues, int paraLength) {
int i, tempPosition;
ListPtr resultPtr = (ListPtr)malloc(sizeof(struct HashList));
resultPtr->length = paraLength;
resultPtr->elements = (NodePtr)malloc(TABLE_SIZE * sizeof(struct Node));
for (i = 0; i < TABLE_SIZE; i++) {
resultPtr->elements[i].key = -1;
resultPtr->elements[i].value = 'x';
}
for (i = 0; i < paraLength; i++) {
tempPosition = paraKeys[i] % TABLE_SIZE;
while (resultPtr->elements[tempPosition].key != -1) {
tempPosition = (tempPosition + 1) % TABLE_SIZE;
printf("Collision, move forward for key %d.\r\n", paraKeys[i]);
}
resultPtr->elements[tempPosition].key = paraKeys[i];
resultPtr->elements[tempPosition].value = paraValues[i];
}
return resultPtr;
}
char hashSearch(ListPtr paraPtr, int paraKey) {
int tempPosition = paraKey % TABLE_SIZE;
while (paraPtr->elements[tempPosition].key != -1) {
if (paraPtr->elements[tempPosition].key == paraKey) {
// printf("Found\r\n");
return paraPtr->elements[tempPosition].value;
}
// printf("Not this one for %d.\r\n", paraKey);
tempPosition = (tempPosition + 1) % TABLE_SIZE;
// printf("Looking at position %d\r\n", tempPosition);
}
return 'x';
}
void hashSearchTest() {
int tempUnsortedKeys[] = { 16, 33, 38, 69, 57, 95, 86 };
char tempContents[] = { 'h', 'e', 'l', 'o', 'w', 'r', 'd' };
ListPtr tempPtr = initList(tempUnsortedKeys, tempContents, 7);
printf("Search result of 95 is: %c\r\n", hashSearch(tempPtr, 95));
printf("Search result of 38 is: %c\r\n", hashSearch(tempPtr, 38));
printf("Search result of 57 is: %c\r\n", hashSearch(tempPtr, 57));
printf("Search result of 4 is: %c\r\n", hashSearch(tempPtr, 4));
}
int main() {
hashSearchTest();
return 1;
}
运行结果
Collision, move forward for key 57.
Collision, move forward for key 95.
Collision, move forward for key 95.
Search result of 95 is: r
Search result of 38 is: l
Search result of 57 is: w
Search result of 4 is: x
代码解说
哈希表(Hash Table)是一种非常重要的数据结构,它使用哈希函数(Hashing Function)将键(key)映射到存储桶(bucket)中,从而实现数据的快速存储、查找、删除等操作。哈希表在平均情况下能够实现O(1)的查找、插入和删除时间复杂度,因此被广泛应用于各种场景,如缓存系统、数据库索引、编程语言中的字典等。