存疑记录

刷题碰到的

解决哈希冲突-公共溢出区法

image-20210921020227197

image-20210921020240377

https://blog.csdn.net/ycwasdfasdf/article/details/52232502

image-20210921020448550

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//https://blog.csdn.net/HLW0522/article/details/52086598
#include<iostream>
using namespace std;
#define HASHSIZE 10
#define NULLKEY -32768
typedef struct hash
{
int *element;
int *extraElement;//溢出区表
int count; // 溢出区的元素个数
}HashTable;
// 由于 通过哈希函数 计算后的地址重复几率很小,所以把重复部分用顺序表来存放,查找时遍历这个公共溢出区的顺序表,效率会更高。
void Init(HashTable *p)
{
p->element = (int*)malloc(sizeof(int)*HASHSIZE);
p->extraElement = (int*)malloc(sizeof(int)*HASHSIZE);
for (int i = 0; i < HASHSIZE; ++i)
{
p->element[i] = NULLKEY;
p->extraElement[i] = NULLKEY;
}
p->count = 0;
}
// 除留余数法
int HASH(int key)
{
return key%HASHSIZE;
}
//插入元素
void InsertHash(HashTable *p, int key)
{
int addr = HASH(key);
//处理冲突, 使用公共溢出法
if (p->element[addr] == NULLKEY)
p->element[addr] = key;
else //如果元素内已经有值了,就放到溢出部分的表中,且把count加 1
p->extraElement[p->count++] = key;
}
int Search(HashTable *p, int key)
{
int addr = HASH(key);
if (key == p->element[addr])
return addr;
else
{
for (int i = 0; i < p->count; ++i)
if (p->extraElement[i] == key)
{
cout << "溢出表" << endl;
return i;
}
}
return -1;
}
int main(void)
{
int a[10] = { 12,45,2,6,78,9,0,1,15 };
HashTable table;
Init(&table);
for (int i = 0; i < 10; i++)
InsertHash(&table, a[i]);

int res = Search(&table, 2);
if (res != -1)
cout << "查找成功!地址为: " << res << endl;
else
cout << "查找失败! " << endl;
system("pause");
return 0;
}