Skip to content

Instantly share code, notes, and snippets.

@bwangelme
Last active September 5, 2018 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwangelme/692492f7d74dc1fce3de259d2478d248 to your computer and use it in GitHub Desktop.
Save bwangelme/692492f7d74dc1fce3de259d2478d248 to your computer and use it in GitHub Desktop.

书中原文如下:

我照着实现了一下哈希表的Init函数(参考 hashTable.c 文件),书中p114页说第18行的malloc调用方式比较低效,可以在循环外调用t->lists = malloc(t->tableSize) * sizeof(struct ListNode);,然后把18行给删掉。

感觉这明显有问题啊,这样的话,就没有为指向每个链表的指针分配空间,而且这些链表也不一定是连续的啊?

HashTable InitTable(int tableSize) {
auto t = (HashTable)malloc(sizeof(struct HashTbl));
if (t == nullptr) {
FATLN("malloc failed");
}
tableSize = nextPrime(tableSize);
t->tableSize = tableSize;
t->lists = (List *)malloc(sizeof(List) * tableSize);
if (t->lists == nullptr) {
FATLN("malloc failed")
}
t->lists = (List *)malloc(t->tableSize * sizeof(struct ListNode));
for (int i = 0; i < tableSize; i++) {
t->lists[i] = (List)malloc(sizeof(struct ListNode));
if (t->lists[i] == nullptr) {
FATLN("malloc failed");
}
t->lists[i]->next = nullptr;
t->lists[i]->key = 0;
}
return t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment