数据结构9.2--哈希表

一、代码

#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)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值