DS哈希查找--链地址法(表头插入)

#include <iostream>

using namespace std;
const int MIN = 0x3f3f3f3f;

int H(int m) {
    return m % 11;
}
class Node
{
public:
    int num;
    Node* next;
    Node(){num=0;next=NULL;};
    Node(int n)
    {
        num=n;
        next=NULL;
    }
};

class Hash {
private:
    int num;
    Node *hash_table;
public:
    Hash(int n) {
        num = n;
        hash_table = new Node[11];
        while (n--) {
            int number;
            cin >> number;
            int h = H(number);
            Node *node=new Node(number);
            node->next=hash_table[h].next;
            hash_table[h].next=node;
        }
    }
    void search(int target)
    {
        int h=H(target);
        if(hash_table[h].next==NULL)
        {
            Node *new_node=new Node(target);
            hash_table[h].next=new_node;
            cout<<"error"<<endl;
            return;
        }
        else
        {
            int search_num=0;
            Node *p=hash_table[h].next;
            while(true)
            {
                search_num++;
                if(p->num==target)
                {
                    cout<<h<<" "<<search_num<<endl;
                    return;
                }
                p=p->next;
                if(p==NULL)
                {
                    Node *new_node=new Node(target);
                    new_node->next=hash_table[h].next;
                    hash_table[h].next=new_node;
                    cout<<"error"<<endl;
                    return;
                }
            }
        }
    }
};

int main() {
    int n;
    cin>>n;
    Hash hash(n);
    int nn;
    cin>>nn;//查询n次
    while(nn--)
    {
        int target;
        cin>>target;
        hash.search(target);
    }
    return 0;
}

Description

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

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

实现哈希查找功能

Input

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

Output

每行输出对应数据的查找结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值