【问题标题】:There is a problem with the hash table using chaining使用链接的哈希表存在问题
【发布时间】: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 感谢您就问题提供反馈。

标签: c hashtable


【解决方案1】:
#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.他指出了你所有的错误。

【讨论】:

  • 感谢您的帮助 :) 我认为链接,尤其是连接列表,是最有问题的部分。在解决应用问题之前,我应该再复习一遍。
猜你喜欢
  • 2015-07-05
  • 2020-09-03
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
相关资源
最近更新 更多