struct hashLink
{
KeyType key; /*the key is what you use to look up a hashLink*/
ValueType value; /*the value stored with the hashLink, an int in our case*/
struct hashLink *next; /*notice how these are like linked list nodes*/
};
struct hashMap
{
hashLink ** table; /*array of pointers to hashLinks*/
int tableSize; /*number of buckets in the table*/
int count; /*number of hashLinks in the table*/
};我正在尝试用hashLinks遍历hashMap。这是正确的方法吗?hashLinks在数组中,且在链表中可以有更多hashLinks链接到它们。我只是不明白如何让指针指向指针。tableSize是数组中元素的数量。在每个数组位置,可能有更多的hashLinks链接到第一个位置。
for(int i = 0; i < ht->tableSize; i ++)
{
hashLink *current;
if (ht->table[i] != 0)
{
current = ht->table[i];
while(current->next !=0)
{
hashLink *next;
next = current->next;
free(current->key);
free(current);
current = next;
}
free(current->key);
free(current);
}
else
{
continue;
}
counter++;
}
}发布于 2015-05-29 17:13:33
是的,这是可行的,但是你最终得到了一个包含悬空指针的哈希表。此外,正如Joachim所指出的,只要您假设结构中包含的值是合理的,即tableSize包含table中的条目数量,并且hashLink已经正确分配,它就可以工作。
你通过链接的迭代是好的,并且正确地free了表中的所有hashLink。但是,考虑一下迭代之后ht的状态。您根本不会更改ht->table[i]的值,因此在您离开循环之后,指针仍将存储在表中。如果你想重用这个表,当你不再需要它们的时候,你应该将指针设置为0,例如,在current = ht->table[i];之后的某个地方添加ht->table[i] = 0。
如果此方法是表的“析构函数”的一部分(例如,像hashmap_delete(...)这样的方法),那么您可以在完成迭代后简单地free哈希图,即在for-loop之后添加free(ht);。
发布于 2015-05-29 17:28:37
简化版:
for(int i=0; i < ht->tableSize; i++)
{
hashLink *current;
while (ht->table[i] != NULL) {
current = ht->table[i];
ht->table[i] = current->next;
free(current->key);
free(current);
}
}它可以进一步简化为 one loop,但这将作为练习留给读者...
注意:作为一个副作用,这会将ht->table[]中的所有指针设置为NULL;这很好,因为在释放链表之后,它们已经变得陈旧。
https://stackoverflow.com/questions/30524869
复制相似问题