数据结构-散列表 哈希表

最近在看《数据结构与算法》,看到散列表这一章,之前一直听说过哈希表,但是一直不知道它怎么解决冲突的问题,现在看完之后才发现原来是用邻接表来解决冲突的问题

下面是具体的实现

#include <iostream>
#include <cstring>
using namespace std;

//Hash值的计算
static unsigned int Hash(const string& key,int tablesize)
{
    unsigned int HashVal=0;
    for(int i=0;i<key.size();i++)
        HashVal=(HashVal<<5)+key[i];
    return HashVal%tablesize;
}


//节点的定义
struct ListNode
{
    string element;
    ListNode* next;
    ListNode()
    {
        element="";
        next=NULL;
    }
};


//定义hashtable
struct HashTable
{
    int tablesize;
    ListNode* TheLists[100000];
    HashTable()
    {
        tablesize=100000;
        memset(TheLists,0,sizeof(TheLists));
    }
};

//查找函数
ListNode* Find(string& key,HashTable& H)
{
    ListNode* pos,*L;
    L=H.TheLists[Hash(key,H.tablesize)];
    pos=L->next;
    while(pos!=NULL&&pos->element!=key)
        pos=pos->next;
    return pos;
}

//对于给定hash值和字符串来查找
ListNode* Find(string& key,int hash_n,HashTable& H)
{
    ListNode* pos=H.TheLists[hash_n];
    while(pos!=NULL&&pos->element!=key)
        pos=pos->next;
    return pos;
}

//插入
void Insert(string& str, HashTable& H)
{
    ListNode* pos;
    int hash_n=Hash(str,H.tablesize);
    pos=Find(str,hash_n,H);
    if(pos==NULL)
    {
        pos=new ListNode;
        pos->element=str;
        pos->next=H.TheLists[hash_n];
        H.TheLists[hash_n]=pos;
    }
}

//删除
void Delete(string& str,HashTable& H)
{
    int hash_n=Hash(str,H.tablesize);
    ListNode* pos=H.TheLists[hash_n],*tmp=H.TheLists[hash_n];//这里不用Find先找一次是避免遍历两次
    while(pos!=NULL&&pos->element!=str)
    {
        tmp=pos;
        pos=pos->next;
    }
    if(pos!=NULL)
    {
        if(pos==H.TheLists[hash_n])
        {
            H.TheLists[hash_n]=pos->next;
        }
        else
        {
            tmp->next=pos->next;
        }
        delete pos;
    }
}

int main()
{
    HashTable h;
    string s="123";
    string s1="s1";
    Insert(s,h);
    Insert(s1,h);
    for(int i=0;i<100000;i++)
    {
        if(h.TheLists[i]!=NULL)
        {
            cout<<h.TheLists[i]->element<<" "<<i<<endl;
        }
    }
    return 0;
}


经验分享 程序员 微信小程序 职场和发展