给定一个数组x[] = {4, 1, 3, 7, 8, 22, 45, 75}, 哈希函数为H(key) = key*2 % 11,采用链地址法处理哈希冲突。建立哈希表:
#include <bits/stdc++.h>
using namespace std;
const int maxsize = 11;
//哈希函数
int hash(int x) {return x*2 % maxsize;}
struct node {
int val;
node *next;
node() {}
node(int x, node *next) {
this->val = x;
this->next = next;
}
};
node hashtable[maxsize];
int x[] = {4, 1, 3, 7, 8, 22, 45, 75};
void chain() {
for (int i=0; i<maxsize; ++i) hashtable[i].next = NULL;
int n = sizeof(x) / sizeof(int);
for (int i=0; i<n; ++i) {
int addr = hash(x[i]);
auto p = new node(x[i], hashtable[addr].next);
hashtable[addr].next = p;
}
}