1.代码如下
#include <stdio.h>
#include <malloc.h>
#define TABLE_SIZE 19
typedef struct Node
{
char value;
int key;
}Node,*NodePtr;
typedef struct HashList
{
int length;
NodePtr elements;
}HashList,*ListPtr;
ListPtr initList(int* paraKeys, char* paraValues, int paraLength)
{
//initialize
ListPtr resultPtr=(ListPtr)malloc(sizeof(HashList));
resultPtr->length=paraLength;
resultPtr->elements=(NodePtr)malloc(sizeof(Node)*TABLE_SIZE);
int i;
for(i=0;i<TABLE_SIZE;i++)
{
resultPtr->elements[i].key=-1;
resultPtr->elements[i].value='x';
}
//fill the list.
int tempPosition;
for(i=0;i<paraLength;i++)
{
tempPosition=paraKeys[i]%TABLE_SIZE;
//if the position is occupied.
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)
{
return paraPtr->elements[tempPosition].value;
}
tempPosition=(tempPosition+1)%TABLE_SIZE;
}
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 0;
}
2.代码说明
1)初始化时将每一个位置的值和字符初始化为-1和x
2)key%listsize算出位置,如果该位置已经被占用,就挪到下一个位置,如果还是被占用,就不断往下移
3.运行结果
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
--------------------------------
Process exited after 0.1124 seconds with return value 0
请按任意键继续. . .