我遇到了一个问题,即添加到我的链表中的节点不是永久性的。这是我的代码。
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 << ""<< current->value ... 输出正常;但是,正如您在我的方法底部看到的那样,STILL NULL 被打印出来了。
你需要知道的事情......
我正在制作 HashMap 。 我将整个节点数组初始化为 nullptr。在代码中,当我遇到 nullptr 时,我正在创建一个节点。
最佳答案
您需要调整前一个 last 节点上的 next
指针或调整 head。
这是更正后的代码[抱歉进行了无偿的样式清理]:
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";
}
关于c++ - 将节点添加到 LinkedList 不是永久 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815838/