簡體   English   中英

為雙向鏈表實現復制構造函數時遇到問題

[英]Having trouble implementing a copy constructor for a doubly linked list

我正在努力為雙向鏈表實現復制構造函數。 該程序可以編譯,但我在復制構造函數中使用“push_back”function 將新創建的節點添加到列表中時遇到了問題。 下面是有問題的復制構造函數和 push_back 函數。

List::List(const List& rhs) // Copy constructor
{
    //this pointer is for the list that is being copied from
    Node* rhsNodePtr;

    //setting the new pointer to the first node of the old list
    rhsNodePtr = rhs.first;

    //looping until the end of the list
    while(rhsNodePtr != nullptr){

        //declaring new node to copy data into
        Node* newNode = new Node("");

        //copying node data from original list into new node
        newNode->data = rhsNodePtr->data;

        //adding new copied node to a new list
        push_back(newNode->data);

        //advancing the old list pointer location for the loop
        rhsNodePtr = rhsNodePtr->next;
    }
}

void List::push_back(string element)
{ 
   Node* new_node = new Node(element);
   if (last == nullptr) // List is empty
   {  
      first = new_node;
      last = new_node;
   }
   else
   {  
      new_node->previous = last;
      last->next = new_node;
      last = new_node;
   }
}

如果我遺漏了任何相關細節,我深表歉意。 請注意,我不只是在尋找解決方案或更正,而是在解釋為什么 push_back(); function 在我當前的實現中不起作用。

編輯:在調用 push_back function 后,復制構造函數中的 while 循環卡住了。

編輯:“First”和“last”在 List class 聲明中初始化,並且在構造函數中都設置為“nullptr”。

編輯:通過調試器運行后,我了解到在last->next = new_node;

您沒有在復制構造函數中last初始化。 所以 push_back 被調用,里面有垃圾。

順便說一句,我認為不需要newNode並且您沒有釋放它。 你可以push_back(rhsNodePtr->data); 直接地。

您的復制構造函數沒有firstlast初始化(除非您在 class 聲明中這樣做,您沒有顯示),並且它還在每次循環迭代時泄漏一個Node

試試這個:

List::List(const List& rhs)
    : first(nullptr), last(nullptr) // <-- add this if needed
{
    Node* rhsNodePtr = rhs.first;
    while (rhsNodePtr) {
        push_back(rhsNodePtr->data); // <-- no need to allocate a new Node for this call
        rhsNodePtr = rhsNodePtr->next;
    }
}

void List::push_back(string element)
{ 
   Node* new_node = new Node(element);
   new_node->previous = last;
   new_node->next = nullptr; // <-- add this if needed
   if (!first) first = new_node;
   if (last) last->next = new_node;
   last = new_node;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM