测试数据1 输出错误 错误输出: 查找39的哈希地址为:9 期望输出: 查找39失败 测试数据2 输出错误 错误输出: 查找37的哈希地址为:7 期望输出: 查找37的哈希地址为:2
时间: 2024-03-23 11:43:18 浏览: 21
非常抱歉,我的代码有误。经过检查,发现在哈希表的初始化中,没有将所有元素初始化为0,导致后面的查找函数无法正确判断某个位置是否为空。以下是修改后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define HASHSIZE 10 // 哈希表长度为10
typedef int Status;
typedef int ElemType;
typedef struct {
ElemType *elem; // 哈希表存储空间基址
int count; // 当前哈希表中元素个数
} HashTable;
Status InitHashTable(HashTable *hash)
{
hash->elem = (ElemType*)malloc(HASHSIZE * sizeof(ElemType));
if (!hash->elem) {
return -1;
}
for (int i = 0; i < HASHSIZE; i++) {
hash->elem[i] = 0; // 将所有元素初始化为0
}
hash->count = 0;
return 0;
}
int Hash(int key)
{
return key % HASHSIZE; // 除留余数法
}
int HashAddr(HashTable *hash, int key)
{
int addr = Hash(key);
while (hash->elem[addr] != 0 && hash->elem[addr] != key) {
addr = (addr + 1) % HASHSIZE; // 线性探测
}
return addr;
}
Status InsertHash(HashTable *hash, int key)
{
int addr = HashAddr(hash, key);
if (hash->elem[addr] != 0) {
return -1; // 已经存在该元素
}
hash->elem[addr] = key;
hash->count++;
return 0;
}
Status searchHash(HashTable hash, int key, int *addr)
{
*addr = HashAddr(&hash, key);
if (hash.elem[*addr] == key) {
return 0; // 查找成功,返回0
}
return -1; // 查找失败,返回-1
}
int main()
{
HashTable hash;
InitHashTable(&hash);
int key;
scanf("%d", &key);
if (InsertHash(&hash, key) == 0) {
int addr;
if (searchHash(hash, key, &addr) == 0) {
printf("查找%d的哈希地址为:%d\n", key, addr);
} else {
printf("查找%d失败\n", key);
}
} else {
printf("插入失败\n");
}
return 0;
}
```
请再次测试,如果还有问题,请告诉我。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)