2015-11-19 53 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不客氣!我很抱歉。我剛剛編輯了我的帖子,以在首先添加的代碼中添加澄清註釋。 –