2015-11-19 54 views
0

我遇到了一个问题,即添加到我的链表的节点不是永久性的。这是我的代码。将节点添加到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时,我创建了一个节点。

+0

在哪一点你认为代码添加一个节点到链表?它没有。它扫描整个列表,并在经过结尾之后,创建一个节点,但没有办法连接它。 – JSF

+0

这个指数绝对是一样的。而@JSF就是这里的困境。那我该怎么做呢?我想不出一种轻松分享地址的方法。 –

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

对不起,我仍然很难理解这是如何解决当前创建一个新节点但是将它留下的问题,从而使新节点留在内存中的问题。新节点如何分配到userDatabase中? –

+0

OH我看到了!谢谢! –

+0

@Xari不客气!我很抱歉。我刚刚编辑了我的帖子,以在首先添加的代码中添加澄清注释。 –