在c中搜索具有单链表的哈希表



我是C的新手我正在试着检查一个单词是否在我的哈希表中。但我有一个分割错误。

这是我的函数代码如果单词被找到,则应返回true;如果不是,则返回false

bool check(const char *word)
{
// Hashing the word
unsigned int hc = hash(word);
// Creating a node for traversing
node *ch = malloc(sizeof(node));
// Traversing
ch->next = table[hc];
C = false;
while (ch->next != NULL)
{
if (strcasecmp(ch->word, word) == 0)
{
c = true;
break;
}
ch = ch->next;
}
return c;
}

对于初学者来说,该语句中使用的变量C

C = false;

也不是在该语句中使用的变量CCD_ 2

c = true;

宣布。

这种节点的分配

node *ch = malloc(sizeof(node));

没有意义,并产生内存泄漏。

此外,对于给定字符串,函数hash是否返回数组table中的索引的有效值也是不清楚的。

假设函数hash确实返回有效索引,则函数check可以通过以下方式定义

bool check( const char *word )
{
// Hashing the word
unsigned int hc = hash( word );
// Traversing
node *head = table[hc];
while ( head != NULL && strcasecmp( head->word, word ) != 0 )
{
head = head->next;
}
return head != NULL;
}

您的代码有几个问题:

  • 您只需要在创建节点时malloc,例如在表中插入项目时。如果您只想遍历bucket中的列表,请创建一个指针变量,逐个访问所有元素。该变量要么是指向列表中现有节点的指针,要么是NULL
  • 遍历列表时,将孤立地查看节点。在移动到下一个节点之前,不需要访问next

您的功能可能如下所示:

bool check(const char *word)
{
unsigned int hc = hash(word);
node *ch = table[hc];
while (ch != NULL) {
if (strcasecmp(ch->word, word) == 0) {
return true;
}
ch = ch->next;
}
return false;
}

如果hash(word)生成有效的哈希表索引,并且bickets的所有头节点都已初始化为"NULL",则这应该有效。

最新更新