哈希表的常用操作:创建、插入、查找、删除

/*
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;
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值