#include<iostream>
using namespace std;
#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]);
}
// printf("Inserting %d to %d\r\n", paraKeys[i], tempPosition);
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;
// printf("For %d\r\n", paraKey);
// printf("Looking at position %d\r\n", tempPosition);
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 0;
}
在分析这段代码的过程中,我学到了如何使用哈希表来实现快速的查找操作。在这个实现中,哈希表被定义为一个固定长度的数组,每个数组元素是一个节点(Node)结构体,用于存储键值对。通过哈希函数将键映射到数组中的位置,如果该位置已经被占用,就通过线性探测法寻找下一个可用位置。
在初始化哈希表时,程序会预先将数组中的每个节点的键值置为-1和'x',表示空节点。然后通过循环遍历要插入的键值对,计算其在数组中的位置,并处理可能出现的碰撞情况。当需要查找某个键对应的值时,同样通过哈希函数计算其位置,然后线性探测找到对应的节点,最终返回该节点的值。
通过运行hashSearchTest函数,可以测试哈希表的查找功能,验证插入和查找操作的正确性。这段代码虽然简单,但是展示了哈希表的基本原理和实现方式,对于理解数据结构中哈希表的工作原理和应用具有一定的参考意义。在今后的学习和工作中,可以借鉴这段代码的实现思路,进一步深入研究和应用哈希表来提高数据查找的效率和准确性。