因此,我正在尝试计算哈希表中存在的字符串数。出于某种原因,此函数始终返回 0。我曾尝试以稍微不同的方式重写它几次以查找逻辑中的错误,但据我所知,此函数应输出条目数 table 。我真的很感激一些帮助,因为这变得非常令人沮丧!谢谢!
/* htbl_n_entries : htbl* -> unsigned int */
/* return the number of entries in all buckets */
unsigned int htbl_n_entries(htbl *t){
int i;
int nbucks = t->n_buckets;
sll**bucks= t->buckets;
unsigned int sum = 0;
for (i = 0; i < nbucks; ++i)
{
while(bucks[i] != NULL){
sum++;
bucks[i] = bucks[i]->next;
}
}
return sum;
}
最佳答案
代码中的 while 将每个 bucks[i].
设置为 NULL 尝试:
sll**bucks= t->buckets;
unsigned int sum = 0;
for (i = 0; i < nbucks; ++i)
{
sll*bucks_= bucks[i];
while(bucks_ != NULL){
sum++;
bucks_ = bucks_->next;
}
}
这只是一个错误,但不解释为什么返回 0。它第一次正确计数,但任何其他时间都是 0。我的猜测是你在其他函数中有类似的错误,此时你的表是已经坏了。
关于计算哈希表中字符串的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15166329/