散列表(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)<<" ";
}
本文参考链接及学习资料:
【2】https://github.com/kele1997/talk_is_cheap/blob/master/data_structure/hashtable/hash_table.cpp