数据结构->9.2哈希表

1.哈希表代码实现

代码如下(示例):

#include <stdio.h>
#include <malloc.h>

#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 tempPosition;
	ListPtr resultPtr = (ListPtr)malloc(sizeof(HashList));

	resultPtr->length = paralength;
	resultPtr->elements = (NodePtr)malloc(TABLE_SIZE * sizeof(Node));

	int i;
	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]);
		}

		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 1;
}

2.输出结果

代码如下(示例):

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

总结

1.哈希表内在就是利用空间换时间,也就是定义的空间足够大,可以只需要一次查询就能找到要找的元素内容。
2.实现:
(1)创建一个包含length,elements元素的结构体,length定义一个大小合适的空间,待会儿分配给elements相应的空间。
(2)利用ListPtr指针指向一个包含有key,value的结点,也就是给输入的内容存储在elements.key和elements.value中。
(3)只讲一下结构怎么定义,算法就不详细说明了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值