将节点添加到 LinkedList 不是永久 C++
Adding Node to LinkedList Not Permanent 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";
}
到目前为止,输出 current->key << " " << current->value ... 输出正常;但是,正如您在我的方法底部看到的那样,打印出 STILL NULL。
你需要知道的事情...
我正在制作哈希图。
我将整个节点数组初始化为 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";
}
我遇到了一个问题,即添加到我的链表中的节点不是永久性的。这是我的代码。
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。
你需要知道的事情...
我正在制作哈希图。 我将整个节点数组初始化为 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";
}