繁体   English   中英

使用链接的哈希表有问题

[英]There is a problem with the hash table using chaining

#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;
      }
   }
}

我使用链接制作了一个哈希表,但是有一个问题。 如果按照主函数输入并打印结果值,则视为碰撞的部分不会出现。 请告诉我输入功能或打印功能是否有问题。

#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. 他指出了你所有的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM