#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct node
{
T val;
node<T>* next;
node(T val):val(val),next(nullptr) {}
};
template<typename T>
class hashmap
{
private:
int sz;
node<T>** hhmp;
public:
hashmap(const hashmap& hm) //拷贝构造函数
{
sz=hm.sz;
hhmp=(node<T>**)malloc(sizeof(node<T>*)*sz);
for(int i=0; i<sz; i++)
{
hhmp[i]=nullptr;
}
for(int i=0; i<sz; i++)
{
if(hm.hhmp[i]!=nullptr)
{
hhmp[i]=new node<T>(hm.hhmp[i]->val);
node<T>* temp1=hhmp[i];
node<T>* temp2=hm.hhmp[i]->next;
while(temp2)
{
temp1->next=new node<T>(temp2->val);
temp2=temp2->next;
temp1=temp1->next;
}
}
}
}
hashmap& operator=(const hashmap& hm)
{
}
hashmap(int sz=10):sz(sz) //重载构造函数
{
hhmp=(node<T>**)malloc(sizeof(node<T>*)*sz);
for(int i=0; i<sz; i++)
{
hhmp[i]=nullptr;
}
}
int hash_func(T key) //哈希函数
{
return key%sz;
}
void myinsert(T num) //插入
{
int hash_key=hash_func(num);
node<T>* temp=new node<T>(num);
temp->next=hhmp[hash_key];
hhmp[hash_key]=temp;
}
bool mysearch(T num) //查找
{
int hash_key=hash_func(num);
if(hhmp[hash_key]==nullptr)
{
return false;
}
node<T> *temp=hhmp[hash_key];
while(temp)
{
if(temp->val==num)
{
return true;
}
temp=temp->next;
}
return false;
}
bool mydelete(T num) //删除
{
int hash_key=hash_func(num);
if(hhmp[hash_key]==nullptr)
{
return false;
}
node<T>* pre=hhmp[hash_key];
if(pre->next==nullptr)
{
if(pre->val==num)
{
hhmp[hash_key]=pre->next;
delete pre;
return true;
}
else
{
return false;
}
}
else
{
node<T>* cur=pre->next;
while(cur)
{
if(cur->val==num)
{
pre->next=cur->next;
delete cur;
return true;
}
else
{
pre=cur;
cur=cur->next;
}
}
}
return false;
}
void print() //打印
{
for(int i=0; i<sz; i++)
{
cout<<i<<" ";
if(hhmp[i]==nullptr)
{
cout<<endl;
}
else
{
node<T>* temp=hhmp[i];
while(temp)
{
cout<<temp->val<<" ";
temp=temp->next;
}
cout<<endl;
}
}
cout<<endl;
}
};
int main()
{
hashmap<int> hm;
hm.myinsert(1);
hm.myinsert(2);
hm.myinsert(3);
hm.print();
hm.mydelete(3);
hm.print();
hashmap<int> hm1=hm;
hm1.print();
return 0;
}
如果有不对的地方,欢迎批评指正!