1.代码如下
#include <stdio.h>
#include<malloc.h>
#define TABLE_SIZE 19
typedef struct Node{
int Key;
char value;
}Node,*NodePtr;
/**
*<key,value>pair.
*/
typedef struct hashList{
int length;
NodePtr elements;
}hashList,*ListPtr;
/**
*Initaliize a data array.
*/
ListPtr initList(int *paraKeys,char *paraValues,int paraLength){
int i,tempPosition;
ListPtr resultPtr=(ListPtr)malloc(sizeof(struct hashList));
//step1.initalize.
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
//step2.fill the data.
for(i=0;i<paraLength;i++){
//Hash
tempPosition = paraKeys[i] %TABLE_SIZE;
//find an empty position.
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
/**
*hashSearch.
*
*@param paraKey The given key.
*@return The content of the key.
*/
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','i','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
/**
*The ebtrance of the program;
*/
int main() {
hashSearchTest();
return 1;
}//of main
2.运行结果
3.小结
实现细节
动态调整哈希表大小(如自动扩容或缩容)可以维持高效性能。
优点
查找、插入和删除操作的平均时间复杂度可以达到O(1),在理想情况下非常高效。