Jacob Macallan
Jacob Macallan

Reputation: 979

Adding Node to LinkedList Not Permanent C++

I'm having a problem where the node being added to my linkedlist is not permanent. Here is my code.

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";
}

So far the output current->key << " " << current->value ... outputs just fine; however, as you can see at the bottom of my method what happens is STILL NULL gets printed out.

Things you need to know...

I'm making a hashmap. I initialized my entire array of Nodes to nullptr. In the code there I'm creating a node when I encounter nullptr.

Upvotes: 0

Views: 66

Answers (1)

Craig Estey
Craig Estey

Reputation: 33601

You need to either adjust the next pointer on the previous last node or adjust the head.

Here's the corrected code [sorry for the gratuitous style cleanup]:

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";
}

Upvotes: 2

Related Questions