#include <iostream>
#define HASH_SIZE 11
using namespace std;
enum{ERROR,OK};
enum{UNSUCCESS,SUCCESS};
enum state{EMPTY,EXIT,DELETE};
using KeyType=string;
typedef struct {
KeyType key;
enum state sign;
}NodeSq;
typedef struct {
NodeSq* elem; //数组元素存储基址
int count; //当前数据元素个数
int size; //当前容量
}HashTable;
bool initHash(HashTable& h);
int Hash(const KeyType& k);
void reMalloc(HashTable& h);
bool insert(HashTable& h, const KeyType& k);
void collision(int& p);
int find(HashTable& h, const KeyType& k, int& pos);
bool deleteHash(HashTable& h, const int& p);
void show(HashTable& h);
bool initHash(HashTable& h) {
//h.elem = (NodeSq*)malloc(HASH_SIZE * sizeof(NodeSq));
h.elem = new NodeSq[HASH_SIZE];
//注意:如果是使用string类型,它的内存是动态分配的,
//根据实例化时确定具体大小。而使用malloc无法进行动态内存分配,只能改为new.
if (!h.elem) {
return ERROR;
}
h.count = 0;
h.size = HASH_SIZE;
for (int i = 0; i < HASH_SIZE; ++i) {
h.elem[i].sign = EMPTY;
}
return OK;
}
//开放定址法求哈希地址
int Hash(const KeyType& k) {
return (k[0] - 'a')%HASH_SIZE;
}
void reMalloc(HashTable& h) {
//重新开辟空间
}
bool insert(HashTable& h, const KeyType& k) {
if (h.count >= h.size) {
reMalloc(h);
return ERROR;
}
int pos;
if (find(h, k,pos)) {
return OK; //表中已有与k相同关键字的元素
}
h.elem[pos].key = k;
h.elem[pos].sign = EXIT;
h.count++;
return OK;
}
//线性探测再散列求得下一探查地址
void collision(int& p) {
p = (p + 1) % HASH_SIZE;
}
//在开放地址哈希表h中查找关键字为k的元素,若查找成功,返回SUCCESS,以p指示待查数据
//若查找不成功,返回UNSCCESS,以p指示插入位置
int find(HashTable& h, const KeyType& k,int& pos) {
pos = Hash(k);
while (h.elem[pos].sign != EMPTY && h.elem[pos].key != k) {
collision(pos);
}
if (h.elem[pos].key == k) {
return SUCCESS;
}
return UNSUCCESS;
}
//懒惰删除:便于查找
bool deleteHash(HashTable& h,const int& p) {
if ((p < 0 || p >= HASH_SIZE)||h.elem[p].sign != EXIT) {
cout << "元素不存在!" << endl;
return ERROR;
}
h.elem[p].sign = DELETE;
return OK;
}
void show(HashTable& h) {
for (int i = 0; i < HASH_SIZE; ++i) {
cout << i << " \t";
}
cout << endl;
for (int i = 0; i < HASH_SIZE; ++i) {
if (h.elem[i].sign == EXIT) {
cout << h.elem[i].key << " \t";
}
else if (h.elem[i].sign == EMPTY) {
cout << "NULL \t";
}
else{
cout << "DELETE \t";
}
}
cout << endl;
}
int main() {
HashTable h;
int n, p;
initHash(h);
KeyType k;
cout << "请输入需插入哈希表中的元素的个数(字符串):";
cin >> n;
cout << "请输入需插入哈希表中的元素(字符串):";
for (int i = 0; i < n; ++i) {
cin >> k;
insert(h, k);
}
cout << "插入完成后的哈希表:" << endl;
show(h);
cout << endl << "*****************************************" << endl << endl;
cout << "请输入哈希表中需要删除的元素个数:";
cin >> n;
cout << "请输入哈希表中需要删除的元素序号(0-" << HASH_SIZE - 1 << "):";
for (int i = 0; i < n; ++i) {
cin >> p;
deleteHash(h, p);
}
cout << "删除完成后的哈希表:" << endl;
show(h);
}
哈希表代码实现
最新推荐文章于 2023-06-04 10:38:35 发布