今天简单说一下,hash表的实现,在此之前,你首先要明白
1.什么是hash表,它是用来干什么的?
2.什么是查找?什么时候只能用顺序查找?什么时候能用二分查找?
3.什么是冲突?什么是hash码?
同样的,把这些东西弄清楚了,再来看,我实现了一个简单的线性hash表,可以插入,同时也可以快速的查找出来。看代码
#include<iostream>
using namespace std;
template <class T>
struct Hnode{
int flag;
T key;
};
template <class T>
class Linear_hash{
private:
int NN;
Hnode<T> *LH;
public:
Linear_hash(){NN=0;return;}
Linear_hash(int);
void prt_L_hash();
int flag_L_hash();
void ins_L_hash(int (*f)(T),T);//insert the new element
int sch_L_hash(int (*f)(T),T);//search the element
};
template <class T>
Linear_hash<T>::Linear_hash(int m){
int k;
NN=m;
LH=new Hnode<T>[NN];
for(k=0;k<NN;k++)
LH[k].flag=0;
return;
}
template <class T>
void Linear_hash<T>::prt_L_hash(){
int k;
for(k=0;k<NN;k++)
if(LH[k].flag==0)
cout<<"<NULL>"<<" ";
else
cout<<"<"<<LH[k].key<<">";
cout<<endl;
return;
}
template <class T>
int Linear_hash<T>::flag_L_hash(){
int k,count=0;
for(k=0;k<NN;k++)
if(LH[k].flag==0) count=count+1;
return count;
}
template <class T>
void Linear_hash<T>::ins_L_hash(int (*f)(T),T x){
int k;
if(flag_L_hash()==0){cout<<"FULL!!"<<endl;return;}
k=(*f)(x);
while(LH[k-1].flag){
k=k+1;
if(k==NN+1) k=1;
}
LH[k-1].key=x;
LH[k-1].flag=1;
return;
}
template <class T>
int Linear_hash<T>::sch_L_hash(int (*f)(T), T x){
int k;
k=(*f)(x);
while((LH[k-1].flag)&&(LH[k-1].key!=x)){
k=k+1;
if(k==NN+1) k=1;
}
if((LH[k-1].flag)&&(LH[k-1].key==x))
return k;
return 0;
}
然后就是具体的例子
#include"Linear_hash.h"
int hashf(int k);
int main(){
int a[]={9,31,26,19,1,13,2,11,27,16,5,21};
int k;
Linear_hash<int> h(12);
cout<<"output the original sequence:"<<endl;
for(k=0;k<12;k++)
cout<<a[k]<<" ";
cout<<endl;
for(k=0;k<12;k++)
h.ins_L_hash(hashf,a[k]);
cout<<"ouput the keyword in the hashtable:"<<endl;
h.prt_L_hash();
cout<<"the location in the hashtable"<<endl;
for(k=0;k<12;k++)
cout<<h.sch_L_hash(hashf,a[k])<<" ";
cout<<endl;
return 0;
}
int hashf(int k){return (k/3+1);}
简单说一下,hash表的出现就是为了提高查找效率,也许有的同学或许不明白了,hash来hash去的到底在干什么?我举个例子,你就懂了,比如数组a[A,B,C],相信大家很快的就知道,A,B,C它们的位置在哪里?因为就是简单的,1,2,3嘛(顺便说一句,永远记得数组下标从0开始,注意代码中下标的使用),也是这是很自然的,同样的,hash表就是一种,你不习惯,不自然的,也许它是b[C,B,A],它也同样实现了A,B,C的存储,只是hash表用了一种函数,不是你简单的y=x,这里面就是,最后的那个hashf()。
所以,你要想弄清楚它,你必须首先理解,它是用来干什么的?没有,可不可以?
看个结果图