我遇到了一个问题,添加到链接列表中的节点不是永久的。这是我的密码。
void HashMap::add(const std::string& key, const std::string& value) {
int index = hasher(key) % sizeOfBuckets;
Node* current = userDatabase[index];
while (true) {
if (current == nullptr) {
current = new Node;
current->key = key;
current->value = value;
current->next = nullptr;
std::cout << current->key << " " << current->value << " at index " << index << std::endl;
break;
}
current = current->next;
}
if (userDatabase[index] == nullptr)
std::cout << "STILL NULL";
}
到目前为止,输出current->key<lt;"<lt;当前->值输出良好;然而,正如您在我的方法底部看到的那样,结果是仍然为NULL被打印出来。
你需要知道的事情。。。
我正在做一个主题图。我将整个Nodes数组初始化为nullptr。在那里的代码中,当我遇到nullptr时,我正在创建一个节点。
您需要调整上一个最后节点上的next
指针或调整头。
以下是更正后的代码[对免费的样式清理感到抱歉]:
void
HashMap::add(const std::string & key, const std::string & value)
{
int index = hasher(key) % sizeOfBuckets;
Node *current = userDatabase[index];
Node *prev;
// find the "tail" [last node] of the list [if any] --> prev
prev = nullptr;
for (; current != nullptr; current = current->next)
prev = current;
current = new Node;
current->key = key;
current->value = value;
current->next = nullptr;
std::cout << current->key << " " << current->value <<
" at index " << index << std::endl;
// list is non-empty -- append new node to end of list
if (prev != nullptr)
prev->next = current;
// list is empty -- hook up new node as list "head"
else
userDataBase[index] = current;
if (userDatabase[index] == nullptr)
std::cout << "STILL NULL";
}