DS哈希查找与增补

题目描述

给出一个数据序列,建立哈希表,采用求余法作为哈希函数,模数为11,哈希冲突用链地址法和表尾插入

如果首次查找失败,就把数据插入到相应的位置中

实现哈希查找与增补功能

输入

第一行输入n,表示有n个数据
第二行输入n个数据,都是自然数且互不相同,数据之间用空格隔开
第三行输入t,表示要查找t个数据
从第四行起,每行输入一个要查找的数据,都是正整数

输出

每行输出对应数据的查找结果,每个结果表示为数据所在位置[0,11)和查找次数,中间用空格分开

样例输入

6 11 23 39 48 75 62 6 39 52 52 63 63 52

样例输出

6 1 error 8 1 error 8 2 8 1

提示

#include<iostream>
using namespace std;
#define INF 0x3f3f
class CNode
{
public:
    int data;
    CNode *next;
    CNode()
    {
        next=NULL;
    }
    CNode(int n,CNode *x)
    {
        data=n;
        next=x;
    }
};
int findhash(CNode Hash[15],CNode *ptr[15],int h)
{
    int tag=0;
    int times=1;
    if(Hash[h%11].data==h)
    {
        tag=1;
        cout<<h%11<<" "<<times<<endl;
    }
    else
    {
        CNode *p=&Hash[h%11];
        p=p->next;
        while(true)
        {
            times++;
            if(p==NULL)
                break;
            else
            {
                if(p->data==h)
                {
                    tag=1;
                    break;
                }
            }
            p=p->next;
        }
        if(tag==1)
                cout<<h%11<<" "<<times<<endl;
        else
            cout<<"error"<<endl;
    }
    return tag;
}
 
 
int main()
{
    int n;
    cin>>n;
    CNode Hash[15];
    CNode *ptr[15];
    for(int i=0;i<15;i++)
    {
        Hash[i].data=INF;
    }
    for(int i=0;i<n;i++)
    {
        int num;
        cin>>num;
        if(Hash[num%11].data==INF)
        {
            Hash[num%11].data=num;
            ptr[num%11]=&Hash[num%11];
        }
        else
        {
            CNode *p=new CNode();
            p->data=num;
            p->next=NULL;
            ptr[num%11]->next=p;
            ptr[num%11]=p;
        }
    }
    int T;
    cin>>T;
    while(T--)
    {
        int h;
        cin>>h;
        if(findhash(Hash,ptr,h)==0)
        {
            if(Hash[h%11].data==INF)
            {
                Hash[h%11].data=h;
                ptr[h%11]=&Hash[h%11];
            }
            else
            {
                CNode *p=new CNode();
                p->data=h;
                p->next=NULL;
                ptr[h%11]->next=p;
                ptr[h%11]=p;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/SZU-DS-wys/p/12183058.html