1 哈希理论
2 数组实现哈希结构 (C语言)
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
typedef struct pair {
int key; //键值。哈希地址
char element[20]; //数据类型
}DATA,*LPDATA;
typedef struct hashTable {
LPDATA* table; //二级指针,便于初始化,以及判断当前哈希地址是否存在冲突
int divisor; //H(key) = key % p;散列函数
int curSize; //
}HASH,*LPHASH;
LPHASH createHashTable(int p) {
LPHASH hash = (LPHASH)malloc(sizeof(LPHASH));
assert(hash);
hash->curSize = 0;
hash->divisor = p;
hash->table = (LPDATA*)malloc(sizeof(LPDATA) * hash->divisor);
assert(hash->table);
//创建空散列表
for (int i = 0; i < hash->divisor; i++) {
hash->table[i] = NULL;
}
return hash;
}
//查找当前元素的存储地址
//如果当前,地址的内容为空,则说明地址可用(无冲突);
//如果找了一圈地址又回到第一次取余的地址,说明表已满。既,当前地址== 第一次取余地址
int search1(LPHASH hash, int key) {
int pos = key % hash->divisor; //不存在冲突的地址
//冲突时,用开放定址法->线性探测->顺序查看下一个地址
int curPos = pos;
do {
if (hash->table[curPos] == NULL || hash->table[curPos]->key == key)
return curPos; //如果当前,地址的内容为空,则说明地址可用(无冲突); || 键相同,直接覆盖
curPos = (curPos + 1) % hash->divisor;
} while (curPos != pos);//如果找了一圈地址又回到第一次取余的地址,说明表已满。既,当前地址==第一次取余地址
return curPos;
}
void insertDATA(LPHASH hash,DATA data) {
//求hash地址
int pos = search1(hash,data.key);
//不存在冲突
if (hash->table[pos] == NULL) {//当前地址没有元素,那么就插入元素
hash->table[pos] = (LPDATA)malloc(sizeof(DATA));//申请内存
memcpy(hash->table[pos], &data,sizeof(DATA));//内存拷贝#include<string.h>
hash->curSize++;
}
//存在冲突
//1.
else {
//1.键相同,直接覆盖
if (hash->table[pos]->key == data.key) {
#pragma warning(suppress : 4996)
strcpy(hash->table[pos]->element, data.element);//#include<string.h>
}
//2.键不同,满了
else {
printf("hash表满了,无法插入!\n");
return;
}
}
}
void printHash(LPHASH hash){
for (int i = 0; i < hash->divisor;i++) {
if (hash->table[i] == NULL)
printf("NULL\n");
else
printf("%d:%s\n",hash->table[i]->key,hash->table[i]->element);
}
}
int main() {
LPHASH hash=createHashTable(10);
DATA arr[] = {10,"雷电",12,"value",53,"四季",54,"春秋",15,"三餐"};
for(int i=0;i<5;i++)
insertDATA(hash,arr[i]);
printHash(hash);
return 0;
}
3 散列理论 (拉链发、链接发)
结构其实是邻接表;
4 散列实现哈希结构
5 c++ 实现哈希
哈希统计字符串,出现的次数
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
//哈希统计字符串,出现的次数
void create(vector<string>& vec,unordered_map<string,int>& hash)
{
for (int i = 0; i < vec.size(); i++)
{
//find寻找当前字符串是否在hash表里,如果一直找到表尾了,说明不存在;
if (hash.find(vec[i]) != hash.end())
hash[vec[i]]++; //若找到了,次数加一
else
hash[vec[i]] = 1; //若没找到,存入hash表,并且记录一次
}
}
int main()
{
unordered_map<string, int> hash;
vector<string> vec = {"123","456","456","abc","456"};
create(vec, hash);
for (auto& i : hash)
{
cout << i.first << ":" << i.second << endl;
}
}