#include <iostream>
using namespace std;
//哈希函数的构造方法:除留取余法
//处理冲突机制:链地址法
typedef struct _NODE
{
int key;
struct _NODE* next;
}_NODE;
typedef struct Hash_Table
{
_NODE* pChainHash[13];
}Hash_Table;
//初始化哈希表
Hash_Table* InitHashTable()
{
Hash_Table* pHashTable = new Hash_Table;
memset( pHashTable, 0, sizeof(Hash_Table) );
return pHashTable;
}
//在哈希表中查找数据
_NODE* FindDataInHash( Hash_Table* pHashTable, int key )
{
if ( !pHashTable )
return NULL;
_NODE* pNode = NULL;
if ( !(pNode = pHashTable->pChainHash[ key % 13 ] ) )
return NULL;
while ( pNode )
{
if ( pNode->key == key )
return pNode;
pNode = pNode->next;
}
return NULL;
}
//在哈希表中插入数据
bool InsertDataToHash( Hash_Table* pHashTable, int key )
{
if ( !pHashTable )
return false;
if ( NULL != FindDataInHash( pHashTable, key ) )
return false;//数据已在里面
_NODE* pNewNode = new _NODE;
memset( pNewNode, 0, sizeof( _NODE ) );
pNewNode->key = key;
_NODE* pNode = NULL;
pNode = pHashTable->pChainHash[ key % 13 ];
if ( !pNode )
{
pHashTable->pChainHash[ key % 13 ] = pNewNode;
}
else
{
while( pNode->next )
{
pNode = pNode->next;
}
pNode->next = pNewNode;
}
return true;
}
//在哈希表中删除元素
bool DeleteDataInHash( Hash_Table* pHashTable, int key )
{
if ( !pHashTable )
return false;
_NODE* pNode = NULL;
if ( !( pNode = pHashTable->pChainHash[key % 13] ) )//无此数据
return false;
if ( pNode->key == key )//直接定址的数据
{
pHashTable->pChainHash[key % 13] = pNode->next;
delete pNode;
return true;
}
_NODE* pPreNode = pNode;//数据冲突,则在同一线性链表中查找
pNode = pNode->next;
while ( pNode )
{
if ( pNode->key == key )
{
pPreNode->next = pNode->next;
delete pNode;
return true;
}
pPreNode = pNode;
pNode = pNode->next;
}
return false;
}