c++ - 将节点添加到 LinkedList 不是永久 C++

标签 c++ linked-list

我遇到了一个问题,即添加到我的链表中的节点不是永久性的。这是我的代码。

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/

相关文章:

c - 链表 - C - 从节点指针数组正确访问结构节点的值

c++ - 具有返回类型 node* 的函数与 C++ 中的 OOP 结合使用

c++ - 查找具有给定总和的子数组

c++ - readyRead() 在 Qt 中如何工作?

c - 释放链接列表

c++ - 编写 bool 表达式来判断列表是否在增加

c++ - 为什么我的链接列表在函数调用后被删除?

c++ - 具有静态成员实例的单例

c++ - 内联汇编,输出指令

c++ - Live555 在一个 RTSP 流中流式传输实时视频和音频