#include<iostream>
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
#define NULLKEY 0
typedef int KeyType;
typedef struct {
KeyType key;
}RecordType;
typedef struct {
RecordType * HashElem;
int countElem;
int hashSize;
}HashTable;
int hashsize[] = { 17, 19,29, 37,47 };
int curSizeIndex = 0;
int hashLength = hashsize[curSizeIndex];
int RecreateHash(HashTable *ht);
void InitHashTable(HashTable *ht)
{
ht->HashElem = (RecordType *)malloc(sizeof(RecordType) * hashLength);
if (ht->HashElem == NULL) {
cout << "空间不足,申请失败" << endl;
exit(0);
}
ht->hashSize = hashLength;
ht->countElem = 0;
for (int i = 0; i < hashLength; i++)
ht->HashElem[i].key = NULLKEY;
}
void DestroyHashTable(HashTable *ht)
{
free(ht->HashElem);
ht->HashElem = NULL;
ht->countElem = 0;
ht->hashSize = 0;
}
int HashAddr(KeyType key)
{
return (key % hashLength);
}
int InsertHash(HashTable *ht, KeyType e)
{
int addr = HashAddr(e);
while (ht->HashElem[addr].key != NULLKEY) {
if (ht->HashElem[addr].key == e) {
cout << "该元素已经存在,无需插入!" << endl;
exit(0);
}
addr = (addr + 1) % ht->hashSize;
if (addr == HashAddr(e)) {
cout << "已经没有可用的插入位置了" << endl;
RecreateHash(ht);
exit(0);
}
}
ht->HashElem[addr].key = e;
ht->countElem++;
if (ht->countElem == ht->hashSize)
RecreateHash(ht);
return 1;
}
int HashSearch(HashTable *ht, KeyType e)
{
int addr = HashAddr(e);
while (ht->HashElem[addr].key != e) {
if (addr == HashAddr(e) || ht->HashElem[addr].key == NULLKEY)
return -1;
addr = (addr + 1) % ht->hashSize;
}
return addr;
}
int HashSearch2(HashTable *ht, KeyType e)
{
int addr = HashAddr(e);
while (ht->HashElem[addr].key != NULLKEY) {
if (ht->HashElem[addr].key == e)
return addr;
addr = (addr + 1) % ht->hashSize;
}
return -1;
}
int RecreateHash(HashTable *ht)
{
RecordType *oldTemp = ht->HashElem;
int oldLen = ht->hashSize;
curSizeIndex++;
ht->hashSize = hashLength = hashsize[curSizeIndex];
ht->HashElem = (RecordType *)malloc(sizeof(RecordType) * hashLength);
if (ht->HashElem == NULL) {
cout << "空间不足,充创失败" << endl;
ht->HashElem = oldTemp;
ht->hashSize = hashLength = oldLen;
exit(0);
}
for (int i = 0; i < oldLen; i++)
if (oldTemp[i].key != NULLKEY)
InsertHash(ht, oldTemp[i].key);
return 1;
}
void TranverseHash(HashTable *ht)
{
cout << "哈希表中的元素有:" << endl;
for (int i = 0; i < ht->hashSize; i++)
if (ht->HashElem[i].key != NULLKEY)
cout << ht->HashElem[i].key << " ";
}
int main()
{
HashTable ht;
InitHashTable(&ht);
int n;
cin >> n;
KeyType key;
for (int i = 0; i < n; i++) {
cin >> key;
InsertHash(&ht, key);
}
TranverseHash(&ht);
int res = HashSearch(&ht, 100);
if (res == -1)
cout << "查找不到" << endl;
else
cout << "其在地址:" << res << endl;
return 0;
}