#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;
}
}
}
我使用鏈接制作了一個哈希表,但是有一個問題。如果按照main函式輸入并列印結果值,則視為碰撞的部分不會出現。請告訴我是輸入功能還是列印功能的問題。
uj5u.com熱心網友回復:
#include <stdio.h>
#include <stdlib.h>
struct Hashnode{
int value;
struct Hashnode* next;
};
void add(int value);
void print();
struct 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;
struct Hashnode* newNode = (struct Hashnode*)malloc(sizeof(struct Hashnode));
newNode->next = NULL;
newNode->value = value;
if (Hash[hashIndex] == NULL) { //firstValue
Hash[hashIndex] = newNode;
}
else { // if have a value starting chaining
struct Hashnode* temp = Hash[hashIndex];
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void print() {
struct Hashnode* temp;
for (int i = 0; i < 11; i ) {
temp = Hash[i];
while (temp != NULL) {
printf("%d, %d\n", i, temp->value);
temp = temp->next;
}
}
}
你必須做這樣的事情。使用地址來存盤而不是 Hashnode 作為陣列。感謝Eugene Sh.他指出了你所有的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/357614.html
上一篇:負x的泰勒級數e^x的誤差
