一、代码
#include<stdio.h>
#include<malloc.h>
#define TABLE_SIZE 19
typedef struct Node{
int key;
int 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));
//step 1. 初始化
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';
} //of for i
//step 2. 加入数据
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]);
}//of while
resultPtr->elements[tempPosition].key = paraKeys[i];
resultPtr->elements[tempPosition].value = paraValues[i];
} //of for i
return resultPtr;
} //of initList
/**
* 哈希查找
*/
char hashSearch(ListPtr paraPtr, int paraKey){
int tempPosition = paraKey % TABLE_SIZE;
while(paraPtr->elements[tempPosition].key != -1){
if(paraPtr->elements[tempPosition].key == paraKey){
return paraPtr->elements[tempPosition].value;
}//of if
tempPosition = (tempPosition + 1) % TABLE_SIZE;
}// of while
return 'x';
} //of hashSearch
/**
* 测试哈希查找
*/
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));
}// of hashSearchTest
int main(){
hashSearchTest();
return 0;
} // of main
二、运行结果
三、代码说明
1)哈希表:哈希表(Hash Table)又称为散列表。哈希表是一种可以根据以key-value键值对形式存储数据的数据结构,可以通过关键字Key直接找到数据Value的存储位置,而不需要经过任何的遍历和比较。
2)以上代码使用取余数的方式进行数据的存储,当产生冲突时向后移动一位。
在使用时要保证空间足够大,运用空间换时间的方式,所以查找的时间复杂度为O(1)。