#include<iostream>
using namespace std;
class hash
{
private:
struct node
{
int num; //实际存的数
int cnt; //引用计数
node* next;//索引下一结点
node(int n,int c,node* next1) : num(n),cnt(c),next(next1) {};
};
node** buf;
int maxSize;
int curSize;
int hashFn(int n)
{
return(n % maxSize);
}
public:
hash(int n) : buf(new node*[n]),maxSize(n),curSize(0)
{
memset(buf,0,sizeof(node**) * n);
};
~hash()
{
delete[]buf;
}
void insert(int n)
{
int index = hashFn(n);
for(node* first = *(buf + index) ; first; first = first->next)
{
if(first->num == n)
{
++(first->cnt);
return;
}
}
node* t = new node(n,1,*(buf + index));
*(buf + index) = t;
++curSize;
}
void erease(int n)
{
int index = hashFn(n);
//特判第一个结点
node* cur,*pre;
for(pre = cur = *(buf + index); cur ; cur = cur->next)
{
if(cur->num == n)
{
if(--(cur->cnt) == 0) //引用计数为0就要删除
{
//特判第一个结点
if(pre == cur)
{
*(buf + index) = cur->next;
}
else
{
pre->next = cur->next;
}
delete cur;
}
--curSize;
return;
}
pre = cur;
}
}
bool Find(int n)
{
int index = hashFn(n);
for(node* first = *(buf + index) ; first; first = first->next)
{
if(first->num == n)
{
return(first->cnt);
}
}
return(0);
}
int getSize()
{
return(curSize);
}
};
int main()
{
}
哈希表模板
最新推荐文章于 2024-07-24 10:18:54 发布