哈希查找与增补

题目描述

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

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

实现哈希查找与增补功能

输入

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

输出

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

样例输入

6
11 23 39 48 75 62
6
39
52
52
63
63
52
与图的邻接表存储类似
#include<iostream>
using namespace std;
struct Node
{
    int data;
    Node *next;
};
int main()
{
    int key = 11;
    Node *Array[11];
    int n;
    cin >> n;
    int i;
    for (i = 0; i < 11; i++)
    {
        Array[i] = new Node;
        Array[i]->next = NULL;
        Array[i]->data = -1;
    }

    for (i = 0; i < n; i++)
    {
        int yu, x;
        cin >> x;
        yu = x % key;
        Node *q = Array[yu];
        while (q->next)
            q = q->next;
        Node *p = new Node;
        p->data = x;
        p->next = NULL;
        q->next = p;
    }
    int t;
    cin >> t;
    while (t--)
    {
        int x, yu;
        cin >> x;
        yu = x % key;
        Node *q = Array[yu];
        int count = 0;
        while (1)
        {
            if (q->data == x)
            {
                cout << yu << " " << count << endl;
                break;
            }
            if (q->next == NULL)
            {
                cout << "error" << endl;
                Node *p = new Node;
                p->data = x;
                p->next = NULL;
                q->next = p;
                break;
            }
            count++;
            q = q->next;

        }
    }
}

样例输出

6 1
error
8 1
error
8 2
8 1
 
 
原文地址:https://www.cnblogs.com/Liu269393/p/10223385.html