通过链表法解决碰撞,把散列到同一槽中的所有元素都放在一个链表中
定义hash表和基本数据结点
参考http://blog.youkuaiyun.com/feixiaoxing/article/details/6885657
#include<iostream>
using namespace std;
typedef struct _NODE//链表元素
{
int data;
struct _NODE * next;
}NODE;
typedef struct _HASH_TABLE
{
NODE * value[10];//指针数组 相当于指向每个链表的头指针
}HASH_TABLE;
//创建hash表
HASH_TABLE * create_hash_table()
{
HASH_TABLE *pHashTbl = (HASH_TABLE*)malloc(sizeof(HASH_TABLE));
memset(pHashTbl,0,sizeof(HASH_TABLE));
return pHashTbl;
}
//在hash表中寻找数据
NODE * find_data_in_hash(HASH_TABLE * pHashTbl,int data)
{
NODE *pNode;
if(NULL==pHashTbl)
return NULL;
if(NULL==(pNode=pHashTbl->value[data%10]))
return NULL;
while(pNode)
{
if(data==pNode->data)
return pNode;
pNode=pNode->next;
}
return NULL;
}
//在hash表中插入数据
bool insert_data_into_hash(HASH_TABLE *pHashTbl,int data)
{
NODE * pNode;
if(NULL==pHashTbl)
return false;
if(NULL==pHashTbl->value[data%10])//如果头指针为空
{
pNode=(NODE*)malloc(sizeof(NODE));//为结点分派内存空间
memset(pNode,0,sizeof(NODE));
pNode->data=data;
pHashTbl->value[data%10]=pNode;
return true;
}
if(NULL!=find_data_in_hash(pHashTbl,data))
return false;
pNode=pHashTbl->value[data%10];//如果散列到的位置的第一个指针不为空 使pNode指向链表的第一个结点
while(NULL!=pNode->next)
pNode=pNode->next;
pNode->next=(NODE*)malloc(sizeof(NODE));//分派空间
memset(pNode->next,0,sizeof(NODE));
pNode->next->data=data;
return true;
}
//从hash表中删除数据
bool delete_data_from_hash(HASH_TABLE * pHashTbl,int data)
{
NODE * pHead;
NODE * pNode;
if(NULL==pHashTbl || NULL==pHashTbl->value[data%10])
return false;
if(NULL ==(pNode=find_data_in_hash(pHashTbl,data)))//在表中寻找数据
return false;
if(pNode==pHashTbl->value[data%10])//如果所找的数据是第一个数据
{
pHashTbl->value[data%10]=pNode->next;
goto final;
}
pHead=pHashTbl->value[data%10];//如果所找的数据不是第一个数据 用pHead指向链表的第一个数据
while(pNode !=pHead->next)
pHead=pHead->next;
pHead->next=pNode->next;//修改指针
final:
free(pNode);
return true;
}
//输出数据
void show(HASH_TABLE * p)
{
NODE * head;
for(int i=0;i<10;i++)
{
if(p!=NULL)
{
head=p->value[i];
while(head!=NULL)
{
cout<<head->data<<' ';
head=head->next;
}
cout<<endl;
}
}
}
int main()
{
NODE * pp;
int a=0,b=0,c=0;
HASH_TABLE * ptr=create_hash_table();
cout<<"Enter a: ";
for(int i=0;i<20;i++)
{
cin>>a;
insert_data_into_hash(ptr,a);//插入元素
}
cout<<"插入后的散列表为:"<<endl;
show(ptr);//显示元素
cout<<"输入要查找的元素:";
cin>>c;
pp=find_data_in_hash(ptr,c);
if(pp)
cout<<"可以找到此元素"<<endl;
else
cout<<"没有此元素"<<endl;
cout<<"输入要删除的元素: ";
cin>>b;
delete_data_from_hash(ptr,b);
cout<<"删除后的散列表为:"<<endl;
show(ptr);
return 0;
}