• Hash表


    #include "iostream.h"
    #include "fstream.h"
    #include "string.h"
    #define  MaxLen 13
    #define  Div 11//被除数
    typedef struct node
    {
        char name[20];
        int  age;
        bool tag;
    }addrBook;
     
    addrBook *bk=new addrBook[MaxLen];
    addrBook *hashbk=new addrBook[MaxLen];//
    
    void ReadFile(int &n)
    {
       ifstream infile("d:\list.txt");
       n=0;
       while (!infile.eof())
       {
            infile>>bk[n].name;
            infile>>bk[n].age;
            n++;
       }
    }
    
    void DispList(int n)
    {
        for (int i=0;i<n;i++)
            cout<<bk[i].name<<'	'<<bk[i].age<<endl;
    }
    
    int HashFunc(int age)//返回age对应的hash函数值
    {
        int pos=age%Div;
        while(hashbk[pos].tag==1)
            pos=(pos+1)%Div;
        if (hashbk[pos].tag==0)
           return pos;
        else
            return -1;
    }
    void FillHashTable(int n)
    {
        int k;//keep the age
        int pos;
       for (int i=0;i<n;i++)
       {
            k=bk[i].age;
            pos=HashFunc(k);
            if(pos!=-1)
            {
                hashbk[pos]=bk[i];
                hashbk[pos].tag=1;
            }
            else
                cout<<"Table Full!"<<endl;
       }
    }
    int SearchHashTable(int age)
    {
        int pos;
        pos=age%Div;
        while(hashbk[pos].tag==1&&hashbk[pos].age!=age)
            pos=(pos+1)%Div;
        if (hashbk[pos].tag==1&&hashbk[pos].age==age)
           return pos;
        else
            return -1;
    }
    void main()
    {
        int n;
        ReadFile(n);
        DispList(n);
        for (int i=0;i<MaxLen;i++)
           hashbk[i].tag=0;//哈希表中没有此元素
        FillHashTable(n);
        int res;
        res=SearchHashTable(36);
        if(res!=-1)
           cout<<"the result is :
    "<<hashbk[res].name<<'	'<<hashbk[res].age<<endl;
    }
  • 相关阅读:
    Ubuntu20.04安装Docker
    开启企业微信H5页面调试功能
    Python实现图遍历
    Linux命令整理
    BDP数据分析之高级计算
    PowerBI之DAX
    Dundas BI 简介
    tableau的高级计算
    k8s集群创建之后coredns一直处于pending状态
    Gradle打包工具入门
  • 原文地址:https://www.cnblogs.com/ewitt/p/6832872.html
Copyright © 2020-2023  润新知