利用开放定址法实现散列表的创建、插入、删除、查找操作
题目描述:
输入输出:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXTABLESIZE 100
typedef int ElemType;
typedef int Index;
typedef int Position ;
typedef enum {Legitimate,Empty,Delete}EntryType;
typedef struct HashEntry Cell;//散列表单元类型
struct HashEntry {
ElemType data; //存放元素
EntryType Info;
};
typedef struct tbnode* HashTable;//散列表类型
struct tbnode {
int TableSize;
Cell* cells; //存放散列单元数据的数组
};
HashTable CreatTable(int TableSize) {
HashTable H;
int i;
H = (HashTable)malloc(sizeof(struct tbnode));
H->TableSize = TableSize;
H->cells = (Cell*)malloc(H->TableSize * sizeof(Cell));
//初始化
for (i = 0;i < H->TableSize;i++) {
H->cells[i].Info = Empty;
}
return H;
}
int Hash(int key, int TableSize) {
int m = key % TableSize;
return m;
}
Position find(HashTable H, ElemType key) {
Position CPOs, NPos;
int cnt = 1;
NPos = Hash(key, H->TableSize);
while (H->cells[NPos].Info ==Legitimate && H->cells[NPos].data != key) {
cnt++;
NPos += 1;
if (NPos >= H->TableSize) {
NPos = NPos % H->TableSize;
}
}
return cnt;
}
void Insert(HashTable H, ElemType key) {
int p = find(H, key)-1; //冲突次数
int q = Hash(key, H->TableSize);
if (H->cells[q + p].Info != Legitimate) {
H->cells[q + p].Info = Legitimate;
H->cells[q + p].data = key;
}
}
void Dele(HashTable H, ElemType key) {
int p = find(H, key)-1;
int q = Hash(key, H->TableSize);
H->cells[q + p].Info = Delete;
}
int main() {
int n,op,key,s;
int TableSize = 11;
HashTable H = CreatTable(TableSize);
scanf("%d", &n);
while (n--) {
scanf("%d %d", &op, &key);
switch (op) {
case 1:
Insert(H, key);
break;
case 2:
Dele(H, key);
break;
case 3:s=find(H, key);
printf("%d\n", s);
break;
}
}
}