c++编写哈希表

来源:互联网 发布:少儿英语网络课程 编辑:程序博客网 时间:2024/06/08 11:07

         好久没有更新文章了,不知不觉发觉自己已经工作,感慨万千啊,不过,废话少说,还是发一篇自己的最近写的一个哈希表吧,写的不好,好多问题没有得到妥善解决,还望大家多多指教

#include<iostream>#include<string>using namespace std;template <class t1,class t2>struct node{t1 key;t2 data;node *next;};template <class t1,class t2>class hash{public:typedef node<t1,t2>* linknode;typedef node<t1,t2> ln;hash();~hash();void insert(t1 key,t2 data);void remove(t1 key);t2 query(t1 key);private:int func(char *);int func(string);int func(int);int func(char);int func(float);int func(void*);linknode *array;string type;};template<class t1,class t2>hash<t1,t2>::hash(){array=new linknode[10];for(int i=0;i<10;i++){array[i]=0;}}template<class t1,class t2>hash<t1,t2>::~hash(){for(int i=0;i<10;i++){if(array[i]){linknode n=array[i];while(n){linknode n1=n;n=n->next;delete n1;}}}}template<class t1,class t2>void hash<t1,t2>::insert(t1 key,t2 data){int sum=func(key)%10;if(array[sum]){ln *n=new ln;n->key=key;n->data=data;n->next=0;linknode p=array[sum];while(p->next){p=p->next;}p->next=n;}else{ln *n=new ln;n->key=key;n->data=data;n->next=0;array[sum]=n;}}template<class t1,class t2>t2 hash<t1,t2>::query(t1 key){int sum=func(key)%10;linknode p=array[sum];while(p){if(type=="char*"){if(stricmp((char*)(int)p->key,(char*)(int)key)==0){return p->data;}else{p=p->next;}}else if(type=="void*"){if((int)p->key==(int)key){return p->key;}else{p=p->next;}}else{if(p->key==key){return p->data;}else{p=p->next;}}}return 0;}template<class t1,class t2>int hash<t1,t2>::func(int i){type="int";return i;}template<class t1,class t2>int hash<t1,t2>::func(float i){type="float";int s=i*100;return s;}template<class t1,class t2>int hash<t1,t2>::func(char *i){type="char*";int s=strlen(i)*i[0];return s;}template<class t1,class t2>int hash<t1,t2>::func(char i){type="char";int s=(int)i;return s;}template<class t1,class t2>int hash<t1,t2>::func(string i){type="string";int s=i.length()*(int)i[0];return s;}template<class t1,class t2>int hash<t1,t2>::func(void *i){type="void*";int s=(int)i;return s;}template<class t1,class t2>void hash<t1,t2>::remove(t1 key){int sum=func(key)%10;linknode p=array[sum];linknode p1=p;while(p){if(type=="char*"){if(stricmp((char*)(int)p->key,(char*)(int)key)==0){if(array[sum]==p){linknode p2=p;array[sum]=p->next;delete p2;}else{linknode p2=p;p1->next=p->next;delete p2;}return;}else{p1=p;p=p->next;}}else if(type=="void*"){if((int)p->key==(int)key){if(array[sum]==p){linknode p2=p;array[sum]=p->next;delete p2;}else{linknode p2=p;p1->next=p->next;delete p2;}return ;}else{p1=p;p=p->next;}}else{if(p->key==key){if(array[sum]==p){linknode p2=p;array[sum]=p->next;delete p2;}else{linknode p2=p;p1->next=p->next;delete p2;}return ;}else{p1=p;p=p->next;}}}return ;}main(){hash<char *,char *> h;h.insert("sds","etew");h.insert("45","45");h.insert("4.5765k","2");h.insert("$345","6");h.insert("43.r","55");h.insert("sx","24");h.remove("$345");cout<<h.query("43.r");}


           本文有不足之处,还望大家多多指正。

原创粉丝点击