刷题碰到的
解决哈希冲突-公共溢出区法


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

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