我遇到了一个问题,即添加到我的链表的节点不是永久性的。这是我的代码。将节点添加到LinkedList不是永久的C++
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";
}
到目前为止输出电流 - >键< < “” < <电流 - >值...输出就好了;但是,正如你可以在我的方法底部看到的那样,STILL NULL被打印出来。
你需要知道的事情...
我在做一个hashmap。 我将整个节点数组初始化为nullptr。在代码中,当我遇到nullptr时,我创建了一个节点。
在哪一点你认为代码添加一个节点到链表?它没有。它扫描整个列表,并在经过结尾之后,创建一个节点,但没有办法连接它。 – JSF
这个指数绝对是一样的。而@JSF就是这里的困境。那我该怎么做呢?我想不出一种轻松分享地址的方法。 –
是的,我绝对无法解决这个问题。我想我可以在不同的代码块中创建第一个节点,从而以这种方式分配内存。 –