/*
Author:Ibsen
Data:2015.12.21
*/
//哈希表的创建、插入、查找、删除(保留余数法建表,线性探查法解决哈希冲突哈希冲突)
#include <iostream>
using namespace std;
const int M=1000; //定义哈希表最大长度
const int P=13; //保留余数法的除数
typedef struct node
{
int key; //关键字
int count; //探查次数
}HashTable[M];
int len=13,m=0; //哈希表的长度和元素个数
int A[M]={16,74,60,43,54,90,46,31,29,88,77},n=11;
//定义空关键字为-1,被删除的关键字为-2.
int Search_HT(HashTable ha,int k)
{//查找元素
int post=k%P;
for(int i=0;ha[post].key!=-1&&ha[post].key!=k;i++)
post=(post+1)%P;
if(ha[post].key==k) return post; //查找成功
else return -1; //查找失败
}
int Delete_HT(HashTable ha,int k)
{//删除元素
int post=Search_HT(ha,k);
if(post!=-1)
{
ha[post].key=-2;
m--;
return 1; //删除成功
}
else return 0; //删除失败(未找到关键字)
}
void Insert_HT(HashTable ha,int k)
{//插入关键字
int post=k%P;
if(ha[post].key==-1||ha[post].key==-2)
{
ha[post].key=k;
ha[post].count=1;
}
else //发生哈希冲突时采用线性探查法解决冲突
{
int cnt=1; //插入k时发生冲突的次数
do
{
post=(post+1)%P;
cnt++;
}while(ha[post].key!=-1&&ha[post].key!=-2);
ha[post].key=k;
ha[post].count=cnt;
}
m++;
}
void Creat_HT(HashTable ha,int A[],int n)
{//创建哈希表
for(int i=0;i<M;i++)
{
ha[i].key=-1;
ha[i].count=0;
}
for(int i=0;i<n;i++)
Insert_HT(ha,A[i]);
}
void Display_HT(HashTable ha)
{//打印哈希表
cout<<"The unmber of keys in HashTable is:"<<m<<endl;
for(int i=0;i<len;i++)
cout<<ha[i].key<<" "<<ha[i].count<<endl;
cout<<endl;
}
int main()
{
HashTable ha;
Creat_HT(ha,A,n);
Display_HT(ha);
int k;
cout<<"Search in HashTable:"<<endl;
while(cin>>k&&k)
{
int pos=Search_HT(ha,k);
if(pos>-1) cout<<"The postion of the key is:"<<pos<<endl;
else cout<<"Search Fail(No key exit)!"<<endl;
}
cout<<"Insert keys to HashTable:"<<endl;
while(cin>>k&&k)
{
Insert_HT(ha,k);
Display_HT(ha);
}
cout<<"Delete keys in HashTable:"<<endl;
while(cin>>k)
{
if(Delete_HT(ha,k))
{
cout<<"Delete Succeed!";
Display_HT(ha);
}
else cout<<"Display Fail(No key exit)!"<<endl;
}
return 0;
}
哈希表的常用操作:创建、插入、查找、删除
猜你喜欢
转载自blog.csdn.net/AC_Gibson/article/details/50371369
今日推荐
周排行