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

时间:2015-11-19 22:51:01

标签: 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-&gt;键&lt;&lt; &#34; &#34; &LT;&LT; current-&gt; value ... 输出就好了;但是,正如你可以在我的方法的底部看到的那样, STILL NULL 会被打印出来。

你需要知道的事情......

我正在制作一个hashmap。 我将整个节点数组初始化为nullptr。在代码中,当我遇到nullptr时,我正在创建一个节点。

1 个答案:

答案 0 :(得分:2)

您需要调整前一个节点上的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";
}
相关问题