【问题标题】:Having trouble implementing a copy constructor for a doubly linked list为双向链表实现复制构造函数时遇到问题
【发布时间】:2019-09-24 21:14:30
【问题描述】:

我正在努力为双向链表实现复制构造函数。该程序可以编译,但我在使用复制构造函数中的“push_back”函数将新创建的节点添加到列表中时遇到了问题。下面是有问题的复制构造函数和 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();函数在我当前的实现中不起作用。

编辑:在调用 push_back 函数后,复制构造函数中的 while 循环卡住了。

编辑:“First”和“last”在 List 类声明中初始化,并且在构造函数中都设置为“nullptr”。

编辑:通过调试器运行后得知last->next = new_node;行中的push_back函数发生了非法内存访问(segmentation fault)

【问题讨论】:

    标签: c++ linked-list copy-constructor


    【解决方案1】:

    您没有在复制构造函数中初始化last。所以 push_back 被调用,里面有垃圾。

    顺便说一句,我不认为需要 newNode 并且您没有释放它。你可以直接push_back(rhsNodePtr->data);

    【讨论】:

      【解决方案2】:

      您的复制构造函数没有初始化 firstlast(除非您在类声明中这样做,您没有显示),并且它还在每次循环迭代时泄漏 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;
      }
      

      【讨论】:

      • 更新了我的代码以反映您所做的更改。通过调试器运行它后,if(last) last-&gt;next = new_node; 行中似乎存在非法内存访问,这也发生在我原来的 push_back 实现中。
      • 这意味着您的其他List 方法没有正确管理last,导致它指向无效的Node。或者,如果您在无效的 List 对象上调用 push_back()。使用您的调试器进行验证。
      • 在阅读了您的建议后,我注释掉了我的“擦除”功能并且程序运行没有问题,所以该功能一定有问题。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 2017-09-13
      相关资源
      最近更新 更多