数据结构:哈希表(除留取余法--链地址法)

#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;
}

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值