//--------------------------------------------------------------------------
//本例中采用链式解决冲突,便于查找
//hash表适合存储和查找操作
//构建hash要尽量减少冲突,hash表空间开的大一点,用空间换时间
//hash表的一种变种是位图表,stl中的bitmap<>,多用于大数据查找问题
//---------------------------------------------------------------------------
#ifndef _HASH_H
#define _HASH_H
#include<iostream>
using namespace std;
const int HASH_SIZE = 11;
typedef struct linknode{
int data;
struct linknode *next ;
}hashnode,*phashnode;
class HASH{
public:
phashnode initHash(); //hash表的初始化
void createHash(int arr[], int size, phashnode _hash); //hash表的构建
int hash_func(int value); //hash函数
int searchHash(phashnode _hash, int value); //hash表的查找
};
phashnode HASH::initHash() {
int i;
phashnode myhash= new hashnode[HASH_SIZE];
if(!myhash) {
return NULL;
}
for(i=0;i<HASH_SIZE;++i) {
myhash[i].data=-1;
myhash[i].next=NULL;
}
return myhash;
}
int HASH::hash_func(int value) {
return value%HASH_SIZE;
}
void HASH::createHash(int arr[], int size,phashnode _hash) {
int i;
for(i=0;i<size;++i) {
int key = hash_func(arr[i]);
phashnode tmp = _hash+key;
if( -1 == tmp->data ) {
tmp->data = arr[i];
}
else {
phashnode newnode = new hashnode;
newnode->data=arr[i];
newnode->next=NULL;
while( NULL != tmp->next ) {
tmp=tmp->next;
}
tmp->next=newnode;
}
}
}
int HASH::searchHash(phashnode _hash, int value) {
int key = hash_func(value);
cout<<"value in hash:"<<_hash[key].data<<endl;
if( -1 == _hash[key].data ) {
return -1;
}
phashnode tmp=_hash+key;
while(NULL!=tmp && value != tmp->data ) {
tmp=tmp->next;
}
if(NULL==tmp) {
return -1;
}
else {
return 1;
}
}
#endif
#include"hash.h"
int main() {
int arr[]={1,2,3,4,5,6,7,8,9,13};
int size=sizeof(arr)/sizeof(int);
int i;
int value=13;
HASH * _hash = new HASH;
phashnode myhash = _hash->initHash();
_hash->createHash(arr,size,myhash);
cout<<_hash->hash_func(value)<<endl;
for(i=0;i<size;++i) {
cout<<myhash[i].data<<" ";
}
cout<<""<<endl;
cout<<_hash->searchHash(myhash,value)<<endl;
delete _hash;
_hash=NULL;
system("pause");
return 1;
}