#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;
}
}
}
I made a hash table using chaining, but there is a problem. If you enter according to the main function and print the result value, the part treated as a collision does not appear. Please tell me if it's a problem that the input function or print function.
CodePudding user response:
#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;
}
}
}
You must do something like this. Use addresses for storing and not Hashnode as an array. Thanks to Eugene Sh.
he pointed all your mistakes.