现在有一个用来存放整数的Hash表,Hash表的存储单位称为桶,每个桶能放3个整数,当一个桶中要放的元素超过3个时,则要将新的元素存放在溢出桶中,每个溢出桶也能放3个元素,多个溢出桶使用链表串起来。此Hash表的基桶数目为素数P,Hash表的hash函数对P取模。
题目的大致意思就是上述的,下面给出个人的代码:
<pre name="code" class="plain">#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;
#define P 7
#define BUCKET_NODE_SIZE 3
#define NULL_DATA -1
struct bucket_node
{
int data[BUCKET_NODE_SIZE];
struct bucket_node *next;
};
bucket_node hash[P];
void Init_Hash_Table(bucket_node (&hash)[P])
{
int i = 0;
for(i = 0;i < P; ++i){
for(int j = 0;j < BUCKET_NODE_SIZE;++j){
hash[i].data[j] = NULL_DATA;
}
hash[i].next = NULL;
}
}
void Insert_New_Element(int &t)
{
int index = t % P;
int i = 0;
for(i = 0;i < BUCKET_NODE_SIZE;++i){
if(hash[index].data[i] == NULL_DATA){
hash[index].data[i] = t;
return;
}
}
bucket_node *p = &hash[index];
while(p->next != NULL){
p = p->next;
for(int i = 0;i < BUCKET_NODE_SIZE; ++i){
if(p->data[i] == NULL_DATA){
p->data[i] = t;
return;
}
}
}
bucket_node *s = (bucket_node*)malloc(sizeof(bucket_node));
assert(s != NULL);
for(int i = 0; i < BUCKET_NODE_SIZE; ++i){
s->data[i] = NULL_DATA;
}
s->next = NULL;
s->data[0] = t;
p->next = s;
}
void Show_Hash()
{
int i = 0;
for(i = 0; i < P; ++i){
cout << "i = "<< i << " : ";
for(int j = 0; j < BUCKET_NODE_SIZE; ++j){
if(hash[i].data[j] != NULL_DATA){
cout << hash[i].data[j] << " ";
}
}
bucket_node *p = &hash[i];
while(p->next){
p = p->next;
for(int k = 0; k < BUCKET_NODE_SIZE; ++k){
if(p->data[k] != NULL_DATA){
cout << p->data[k] << " ";
}
}
}
cout << endl;
}
cout << endl;
}
测试程序如下:
int main(int argc,char**argv)
{
int array[] = {15,14,21,87,96,293,35,24,149,19,63,16,103,77,5,153,145,356,51,68,705,453 };
int n = sizeof(array) / sizeof(int);
Init_Hash_Table(hash);
for(int i = 0; i < n; ++i){
Insert_New_Element(array[i]);
}
Show_Hash();
return 0;
}
其执行结果如下: