#include <iostream>
#include <ctime>
using namespace std;
#define SUCCESS 1
#define UNSUCCESS 0
#define HASHSIZE 12
#define NULLKEY 0xffffffff/2
typedef struct
{
int *elem;
int count;
}HashTable;
typedef int Status;
Status InitHashTable( HashTable* pHashTable )
{
if ( !pHashTable )
return UNSUCCESS;
pHashTable->count = 0;
pHashTable->elem = new int[HASHSIZE];
for ( int i = 0; i < HASHSIZE; ++i )
pHashTable->elem[i] = NULLKEY;
return SUCCESS;
}
Status ClearHashTable( HashTable* pHashTable )
{
if ( !pHashTable )
delete[] pHashTable;
return SUCCESS;
}
int Hash( int key )
{
return key % HASHSIZE; //除留取余法,根据前辈们的经验,若哈希表长为M,则取余因子P为小于
//或等于表长(最好接近M)的最小质数或不包含小于20质因子的合数
}
Status InsertHashTable( HashTable* pHashTable, int key )
{
if ( !pHashTable )
return UNSUCCESS;
int addr = Hash( key );//求哈希地址
while( pHashTable->elem[addr] != NULLKEY ) //不为空,则冲突了
addr = ( addr + 1)% HASHSIZE; //开放定址法:线性探测
pHashTable->elem[addr] = key;
pHashTable->count++;
return SUCCESS;
}
Status SearchHashTable( HashTable* pHashTable, int key, int *addr )
{
if ( !pHashTable )
return UNSUCCESS;
*addr = Hash( key );
while ( pHashTable->elem[*addr] != key )
{
*addr = (*addr + 1) % HASHSIZE; //开放定址法:线性探测
if ( pHashTable->elem[*addr] == NULLKEY ||
*addr == Hash( key) )
{
return UNSUCCESS;
}
}
return SUCCESS;
}
int main()
{
HashTable _HashTable;
InitHashTable( &_HashTable );
int a[10];
cout<<"请输入集合元素:";
for ( int i = 0; i < 10; i++ )
{
cin>>a[i];
InsertHashTable( &_HashTable, a[i] );
}
int key;
cout<<"请输入要查找的关键字"<<endl;
cin>>key;
int addr;
if ( !SearchHashTable( &_HashTable, key, &addr ) )
return 0;
cout << "元素索引为:" << addr << endl;
return 0;
}
HashTable(散列表)
最新推荐文章于 2024-06-14 23:04:09 发布