zoukankan      html  css  js  c++  java
  • 哈希表(链地址法处理冲突)(1012)

    Description
     

        采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法。建立链表的时候采用尾插法。

    Input
        第一行为哈西表的长度;第二行为关键字的个数n; 第三行为关键字集合; 第四行为要查找的数据。
    Output
        如果查找成功,输出该关键字所在哈希表中的地址和比较次数;如果查找不成功,输出-1。
     
    Sample Input
    1
    2
    3
    4
    5
    13
    13
    16 74 60 43 54 90 46 31 29 88 77 78 79
    16
     
    Sample Output
     
     
     
    1
    3,1
     
     
    #include<iostream>
    #include<cstring>
    using namespace std;
    typedef struct node
    {
        int data;
        struct node *next;
    }Chain;
    typedef struct
    {
        Chain *head[100];
        int len, n;
    }HashTable;
    Chain * tail[100];
    HashTable ha;
    void InsertHT()
    {
        int adr, k;
        Chain *p = new Chain;
        cin >> k;
        adr = k%ha.len;
        p->data = k;
        p->next = NULL;
        if (!ha.head[adr])
        {
            ha.head[adr] = p;
            tail[adr] = ha.head[adr];
        }
        else
        {
            tail[adr]->next = p;
            tail[adr] = p;
        }
    }
    void CreateHT(int len, int n)
    {
        ha.len = len, ha.n = n;
        for (int i = 0; i < n; i++)
            ha.head[i] = NULL;
        for (int i = 0; i < n; i++)
            InsertHT();
    }
    void Search(int x)
    {
        int adr = x%ha.len, flag = 0, cnt = 0;
        Chain *p = ha.head[adr];
        while (p)
        {
            cnt++;
            if (p->data == x)
            {
                flag = 1;
                break;
            }
            else
                p = p->next;
        }
        if (flag)cout << adr << ',' << cnt;
        else cout << "-1";
    }
    int main()
    {
        int len, n, x;
        cin >> len >> n;
        CreateHT(len, n); 
        cin >> x;
        Search(x);
        return 0;
    }
    View Code
     
  • 相关阅读:
    [Linux] Chmod 改变权限
    [linux命令]基本命令
    [Linux命令] 查看目录大小du
    [Linux命令]格式化mkfs
    在VMWare下的Linux切换
    .net的MSMQ异步调用
    CASSINI源代码分析
    [Wix] RadioButton与ListItem的属性要改掉了
    如何快速生成Insert数据插入语句?
    撕纸
  • 原文地址:https://www.cnblogs.com/traini13/p/4579880.html
Copyright © 2011-2022 走看看