哈希表可采用链式结构进行构建。
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";
}
}