it编程 > 软件设计 > 数据结构

-哈希表-

92人参与 2024-08-06 数据结构

代码

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

		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) {
			// 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 1;
}

运行结果

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

代码解说

哈希表(hash table)是一种非常重要的数据结构,它使用哈希函数(hashing function)将键(key)映射到存储桶(bucket)中,从而实现数据的快速存储、查找、删除等操作。哈希表在平均情况下能够实现o(1)的查找、插入和删除时间复杂度,因此被广泛应用于各种场景,如缓存系统、数据库索引、编程语言中的字典等。

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

2. 基础数据结构之哈希表

08-06

算法基础5:哈希表、有序表、链表

08-06

算法数据结构基础——哈希表(Hash Table)

08-06

数据结构学习 jz12字母迷宫

08-06

【数据结构】哈希表上——开放寻址法

08-06

【数据结构】——归并排序和计数排序

08-06

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论