7. 哈希表

哈希表可采用链式结构进行构建。

1.哈希表的结构定义

#include<iostream>
using namespace std;
class Listnode {
public:
	int val;
	Listnode* next;
public:
	Listnode() {
		this->next = NULL;
		this->val = 0;
	}
	Listnode(int x) {
		this->val = x;
		this->next = NULL;
	}
};

2.哈希函数

int hash_fun(int key, int table_len) {
	return key % table_len;
}

3.哈希-头部插入

void insert_head(Listnode* hashtable[], Listnode* node, int table_len) {
	int key = hash_fun(node->val, table_len);
	node->next = hashtable[key];
	hashtable[key] = node;
}

4.哈希查询

bool hash_serach(Listnode* hashtable[], int value, int table_len) {
	int key = hash_fun(value, table_len);
	while (hashtable[key] != NULL) {
		if (value == hashtable[key]->val) {
			return true;
		}
		else {
			hashtable[key] = hashtable[key]->next;
		}
	}
	return false;
}

5.主函数测试哈希表

int main() {
	const int N = 10;
	Listnode* hashtable[N]={0};
	int arr[20] = { 1,2,3,4,5,6,7,8,9,10 ,11,12,13,14,15,16,17,18,19,20 };
	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
		Listnode* node = new Listnode(arr[i]);
		insert_head(hashtable, node,N);
	}
	cout << "打印哈希表" << endl;
	for (int i = 0; i < N; i++) {
		while (hashtable[i] != NULL) {
			cout << hashtable[i]->val<<" ";
			hashtable[i] = hashtable[i]->next;
		}
		cout << endl;
	}

	cout << hash_serach(hashtable,arr[0],N);
	

	return 0;
}

6.数组模拟哈希表(拉链法)

 7. 字符串哈希

1. 字符串变为数字,“123”->123,“abc”->num

2. 此时字符串就是一个X进制的数,同时对Y取模

3.X=131,Y=2的64次方

 

#include<iostream>

using namespace std;

unsigned long long hash_s[100]={0};
unsigned long long p[100];
int P = 131;

unsigned long long find(int l, int r) {
	return hash_s[r] - hash_s[l - 1] * p[r - l + 1];
}

void main() {
	string st1 = "0abcedfabcklooptssdg";
	p[0] = 1;
	for (int i = 1; i < st1.size(); i++) {
		p[i] = p[i-1]*P;
		hash_s[i] = hash_s[i-1]*P+st1[i];
	}

	if (find(1, 3) == find(7, 9)) {
		cout<<"Same";
	}
	else {
		cout << "Error";
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋进在AI路上的小李

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值