数据结构_哈希表

散列表(Hash table,也叫哈希),是根据键(Key)而直接访问在内存存储位置的数据结构。 也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到中一个位置来访问记录,这加快了查找速度。 这个映射函数称做散列函数,存放记录的数组称做散列表。

hash冲突发生的情况是指存在两个值的hashCode相同。

链表法又称拉链法,作用是把具有相同散列地址的关键字(同义词)值放在同一个单链表中,称为同义词链表。代码中使用一个列表,保存所有hashcode相同的值。

//哈希表 的实现
#include <iostream>

using namespace std;

typedef struct node{
    struct node *next;
    int key;
}Node;

typedef struct {
    Node *head;
}HashTable;

void insertHT(HashTable hash[],int &n,int p,int k){
    int index=k%p;
    Node *q=new Node;
    q->next=NULL;
    q->key=k;
    if(hash[index].head==NULL)
        hash[index].head=q;
    else{
        q->next=hash[index].head;
        hash[index].head=q;
    }
    n++;
}


void createHash(HashTable hash[],int &n,int m,int p,int keys[],int n1){
    for(int i=0;i<m;i++){
        hash[i].head==NULL;
    }
    n=0;
    for(int i=0;i<n1;i++)
        insertHT(hash,n,p,keys[i]);
}

bool deleteHash(HashTable hash[],int &n,int m,int p,int key){
    int index=key%p;
    Node* q=NULL,*pre=NULL;
    q=hash[index].head;
    if(q==NULL)
        return false;
    while(q!=NULL){
        if(q->key==key)
        {
            break;
        }
        pre=q;
        q=q->next;
    }
    if(q!=NULL){
        if(pre==NULL){
            Node* tmp=q;
            hash[index].head=tmp->next;
            delete tmp;
            n--;
            return true;
        }else{
            pre->next=q->next;
            delete q;
            n--;
            return true;
        }
    }
    return false;
}


bool searchHash(HashTable hash[],int p,int key){
    Node* q;
    int index=key%p;
    q=hash[index].head;
    while(q!=NULL){
        if(q->key==key)
            break;
        q=q->next;
    }
    if(q!=NULL)
        return true;
    else
        return false;
}

int main(){
    int temp[200];
    HashTable table[100];
    int n=0;
    for(int i=0;i<100;i++)
        temp[i]=i;
    createHash(table,n,100,23,temp,100);
    for(int i=0;i<5;i++){
        cout<<searchHash(table,23,i)<<" ";
    }
    cout<<searchHash(table,23,150)<<" ";
}
本文参考链接及学习资料:

【1】https://github.com/Clayygou/Datawhale-6-programming/blob/master/Task4/%E6%95%A3%E5%88%97%E8%A1%A8%EF%BC%88%E5%93%88%E5%B8%8C%E8%A1%A8%EF%BC%89/1%E3%80%81%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E5%9F%BA%E4%BA%8E%E9%93%BE%E8%A1%A8%E6%B3%95%E8%A7%A3%E5%86%B3%E5%86%B2%E7%AA%81%E9%97%AE%E9%A2%98%E7%9A%84%E6%95%A3%E5%88%97%E8%A1%A8.md

【2】https://github.com/kele1997/talk_is_cheap/blob/master/data_structure/hashtable/hash_table.cpp

猜你喜欢

转载自blog.csdn.net/xiu351084315/article/details/89343164