一、哈希
哈希法又名散列法,是一种特殊的查找方法
哈希法是希望不通过任何的比较,一次存取就得到元素
二、哈希表
哈希表本质上是个数组,底层实现是在数组上然后再加工
实现哈希表的方式:
1)数组 + 链表
2)数组 + 树
哈希表的适用场景:
1) 模拟映射关系:字典、通信薄
2)防止重复:抽奖、投票
3)缓存/记住数据,以免服务器再通过处理来生成它们
三、代码示例
1)哈希表数据结构
//链式结构(用来处理冲突)
struct Node
{
int data;
Node *next;
};
//哈希表数据结构
struct Hash
{
//定义一个指针数组,数组里每个指针指向一个链表
Node *arr[10];
};
2)创建哈希表
//---创建哈希表---
bool createHash(Hash * pHash)
{
if (pHash == nullptr)
return false;
for (int i = 0; i < 10; i++)
{
pHash->arr[i] = new Node;
pHash->arr[i]->data = 0;
pHash->arr[i]->next = nullptr;
}
return true;
}
3)插入数据
//---插入数据---
bool insertHash(Hash *pHash,int insertData)
{
if(pHash == nullptr)//哈希表不存在
return false;
Node *pHead = pHash->arr[insertData % 10];//辅助节点
if (pHead->data == 0)
{
pHead->data = insertData;
return true;
}
Node *pNode = pHead;
while (pNode->next)
{
pNode = pNode->next;
}
pNode->next = new Node;
pNode->next->data = insertData;
pNode->next->next = nullptr;
return true;
}
4)查找数据
//---查找节点---
Node * find(Hash *pHash,int findData)
{
if (pHash == nullptr)
return nullptr;
Node *pHead = pHash->arr[findData % 10];
Node *pNode = pHead;
while (pNode->data != findData)
{
pNode = pNode->next;
if (pNode == nullptr)
{
return nullptr;
}
}
return pNode;
}
5) 删除数据
//---删除节点---
void deleteHash(Hash *pHash,int deleteData)
{
Node *pTemp = find(pHash,deleteData);
if(pTemp == nullptr)
return;
Node *pHead = pHash->arr[deleteData % 10];
Node *pNode = pHead;
if (pHead == pTemp)
{
pHash->arr[deleteData % 10] = pHead->next;
}
else
{
while (pNode->next != pTemp)
{
pNode = pNode->next;
}
pNode->next = pTemp->next;
}
delete [] pTemp;
}
6)清空哈希表
//---清空哈希表---
void clearHash(Hash *& pHash)//注意要引用!!!
{
if (pHash == nullptr)
return;
Node *pHead;
Node *pNode;
for (int i = 0; i < 10; i++)
{
if ((pHead = pHash->arr[i]) != nullptr)
{
while (pHead)
{
pNode = pHead;
pHead = pHead->next;
delete [] pNode;
}
}
}
delete [] pHash;
pHash = nullptr;
}