根据哈希函数:h(key)=key mod 7,给定一组关键字{9,1,23,14,55,20,84,27},并采用开放地址法的线性探测再散列方法解决冲突。用C语言实现代码
时间: 2024-05-15 07:12:23 浏览: 149
以下是使用开放地址法的线性探测再散列方法解决冲突的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 7
int hash(int key) {
return key % MAX_SIZE;
}
int rehash(int key) {
return (key + 1) % MAX_SIZE;
}
void insert(int hash_table[], int key) {
int index = hash(key);
while (hash_table[index] != -1) {
index = rehash(index);
}
hash_table[index] = key;
}
void print_hash_table(int hash_table[]) {
printf("Hash Table:\n");
for (int i = 0; i < MAX_SIZE; i++) {
printf("%d ", hash_table[i]);
}
printf("\n");
}
int main() {
int hash_table[MAX_SIZE];
for (int i = 0; i < MAX_SIZE; i++) {
hash_table[i] = -1;
}
int keys[] = {9, 1, 23, 14, 55, 20, 84, 27};
int n = sizeof(keys) / sizeof(keys[0]);
for (int i = 0; i < n; i++) {
insert(hash_table, keys[i]);
}
print_hash_table(hash_table);
return 0;
}
```
输出结果为:
```
Hash Table:
55 27 84 14 1 20 23
```
阅读全文