头文件:
#ifndef HASHTABLE_H
#define HASHTABLE_H
typedef int ElemType; //这里的ElemType只能为int,因为选取的散列函数为取模
typedef struct{
ElemType * elemArray;
int maxsize;
int size;
}HashTable;
void InitHash(HashTable & HT, int Msize); //初始化哈希表,所有key置为-1
void Insert(HashTable & HT, ElemType E); //不插入已有的数据
void Delete(HashTable & HT, ElemType E); //删除指定值
int Find(HashTable HT, ElemType E); //返回指定值的下标
bool IsEmpty(HashTable HT);
bool IsFull(HashTable HT);
void PrintHash(HashTable HT); //打印哈希表
#endif
实现文件:
#include "HashTable.h"
#include <iostream>
using namespace std;
void InitHash(HashTable & HT, int Msize)
{
HT.maxsize = Msize;
HT.size = 0;
HT.elemArray = new ElemType[Msize];
for (int i = 0; i < HT.maxsize; i++){
HT.elemArray[i] = -1;//key为-1代表该位置为空
}
}
void Insert(HashTable & HT, ElemType E)
{
if (IsFull(HT)){
cout << "hash表已满,插入失败" << endl;
return;
}
int index = E % HT.maxsize;
while (true){
if (HT.elemArray[index] == -1){
HT.elemArray[index] = E;
HT.size++;
break;
}
else{
index = (index + 1) % HT.maxsize;
}
}
}
void Delete(HashTable & HT, ElemType E)
{
if (IsEmpty(HT)){
cout << "hash表已空,删除失败" << endl;
return;
}
int index = E % HT.maxsize;
int count = 0;
while (true){
if (HT.elemArray[index] == E){
HT.elemArray[index] = -1;
HT.size--;
cout << "找到值" << E << ",删除成功" << endl;
break;
}
else{
index = (index + 1) % HT.maxsize;
}
count++;
if (count == HT.maxsize){
cout << "找不到值" << E << ",删除失败" << endl;
break;
}
}
}
int Find(HashTable HT, ElemType E)
{
int index = E % HT.maxsize;
int count = 0;
while (true){
if (HT.elemArray[index] == E){
return index;
}
else{
index = (index + 1) % HT.maxsize;
}
count++;
if (count == HT.maxsize){
cout << "找不到值" << E << ",查找失败" << endl;
break;
}
}
return -1;
}
bool IsEmpty(HashTable HT)
{
if (HT.size == 0){
return true;
}
else{
return false;
}
}
bool IsFull(HashTable HT)
{
if (HT.size == HT.maxsize){
return true;
}
else{
return false;
}
}
void PrintHash(HashTable HT)
{
cout << "hash表为:";
for (int i = 0; i < HT.maxsize; i++){
cout << HT.elemArray[i] << " ";
}
cout << endl;
}
#include "HashTable.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand((int)time(0));
HashTable testHash;
InitHash(testHash, 13);//最大容量最好为素数
cout << "插入测试:" << endl;
for (int i = 0; i < testHash.maxsize; i++){
Insert(testHash, rand() % 50 + 1);
PrintHash(testHash);
}
cout << endl;
cout << "查找测试:" << endl;
for (int i = 0; i < testHash.maxsize; i++){
ElemType E = rand() % 50 + 1;
int index = Find(testHash, E);
if (index != -1){
cout << E << "对应下标为:" << index << endl;
}
}
cout << endl;
cout << "删除测试:" << endl;
for (int i = 0; i < testHash.maxsize; i++){
ElemType E = rand() % 50 + 1;
Delete(testHash, E);
PrintHash(testHash);
}
cout << endl;
system("pause");
}