数组实现为:以8个为例子
#define Max 8
//the size of example
template<class T>
struct node{
T data;
unsigned int flag;
};
node<int> *test=new node<int>[10];
int arr[Max];
//recording some data;
for(int i=0;i<10;i++)
{
test[i].flag=0;
}
int step[Max];
//recording steps of sucess for the hash
cout<<"the num is :\n";
for(int i=0;i<Max;i++)
{
cin>>arr[i];
step[i]=0;
}
cout<<endl;
int j;
for(int i=0;i<Max;i++)
{
j=arr[i]%Max;
if(test[j].flag==0)
{
test[j].data=arr[i];
test[j].flag=1;
step[j]=1;
}
else
while(1){
int k=1;
j=(j+1)%Max;
k++;
if(test[j].flag==0)
{
k++;
test[j].data=arr[i];
test[j].flag=1;
step[j]=k;
break;
}
}
}
for(int i=0;i<Max;i++)
cout<<" "<<test[i].data<<" ";
cout<<endl;
cout<<"the steps of hash(for every number):"<<endl;
for(int i=0;i<Max;i++)
cout<<" "<<step[i]<<" ";
cout<<endl;
double sum=0;
for(int i=0;i<Max;i++)
sum+=step[i];
cout<<"average of sucess acess to hash:"<<sum/Max<<endl;
delete [] test;
return 0;
利用邻接链表实现的
typedef int Element;
struct node{
Element data;
struct node *next;
}Node[5];
void iniList()
{
for(int i=0;i<5;i++)
{
Node[i].data=i;
}
}
//初始化邻接表头节点
void setData(Element data)
{
int index=data%5;
//哈希取得其中的数据
struct node *p=(struct node*)malloc(sizeof(struct node));
p->data=data;
struct node *head=&Node[index];
//邻接表第一个连接是否为空
if(!head->next)
{
head->next=p;
}
else
{
while(head->next)
{
head=head->next;
}
head->next=p;
//这里是为了找出其中的头尾--邻接表
}
}
//输出邻接表的值,打印出来
void show()
{
struct node*p;
int i=0;
p=&Node[0];
//获取头尾的地址
for(;i<5;)
{
p=p->next;
while(p)
{
printf("%d --->",p->data);
p=p->next;
}
printf("the index %d\n",i);
i++;
p=&Node[i];
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int a[]={23,34,56,567,34,23,0,9,9,3,54645,23,3267,56,34,23,45,565,34};
iniList();
for(int i=0;i<19;i++)
setData(a[i]);
show();
return 0;
}