【发布时间】:2021-12-26 18:36:07
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
struct Hashnode* next;
} Hashnode;
void add(int value);
void print();
Hashnode Hash[11];
int main() {
add(12);
add(44);
add(13);
add(88);
add(23);
add(94);
add(11);
add(39);
add(20);
add(16);
add(5);
print();
return 0;
}
void add(int value) {
int hashIndex = value % 11;
Hashnode* newNode = (Hashnode*)malloc(sizeof(Hashnode));
newNode->next = NULL;
newNode->value = value;
if (Hash[hashIndex].value == NULL) { //firstValue
Hash[hashIndex].next = newNode;
}
else { // if have a value starting chaining
Hashnode* temp = Hash[hashIndex].next;
while (temp != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void print() {
Hashnode* temp;
for (int i = 0; i < 11; i++) {
temp = Hash[i].next;
while (temp->next != NULL) {
printf("%d, %d\n", i, temp->value);
temp = temp->next;
}
}
}
我使用链式制作了一个哈希表,但是有一个问题。 如果按主函数进入并打印结果值,则不会出现作为碰撞处理的部分。 请问是输入功能还是打印功能有问题。
【问题讨论】:
-
Hash[hashIndex].value == NULL-value不是要与NULL进行比较的指针。0可能是一个有效值。 -
您的
print函数永远不会打印“第一个”值,因为temp始终初始化为next -
@Eugene Sh.好的,让我解决它。还有其他问题吗?
-
最好将其声明为
Hashnode *Hash[11];(可能带有初始化程序:Hashnode *Hash[11] = {0};)。然后你可以检查Hash[hashIndex]是不是NULL,看看它是否未被使用。 -
@Ian Abbott 感谢您就问题提供反馈。