c++ - 链表的复制构造函数

标签 c++

我的链表类的复制构造函数有问题。 函数正常工作,但 visual studio 调试器有一个“滞后”,所以我可以假设该函数内部发生了一些不好的事情。 我无法捕获错误,而且我不知道我的逻辑有什么问题。 这是代码:

Linked_List::Linked_List(const Linked_List & obj)
   : head(nullptr)
{

Node * currrentNode = obj.head;
Node * lastNode = nullptr;

while (currrentNode != nullptr)
{
    Node * newNode = new Node;
    newNode->character = currrentNode->character;

    if (head != nullptr)
    {
        head = newNode;
        lastNode = head;
    }

    else
    {
        lastNode->next = newNode;
        lastNode = newNode;
    }

    currrentNode = currrentNode->next;
}

}

最佳答案

该代码以错误的方向插入新节点。您正在从前到后循环遍历源列表(正如您应该做的那样),但您正试图以从后到前的顺序将节点插入到目标列表中。但是您根本不会分配 head,并且在它被分配指向节点之前访问 lastNode。更糟糕的是,即使您正确分配了 headlastNode,您也没有更新每个新节点以指向前一个 head 节点当您用新节点替换当前 head 时,它的 next 节点。所以你的目标列表仍然会是格式错误和内存泄漏。

代码应该改为按从前到后的顺序插入新节点:

Linked_List::Linked_List(const Linked_List & obj)
   : head(nullptr)
{
    Node * currentNode = obj.head;
    Node * lastNode = nullptr;

    while (currentNode)
    {
        Node * newNode = new Node;
        newNode->character = currentNode->character;

        if (lastNode)
            lastNode->next = newNode;
        else
            head = newNode;

        lastNode = newNode;
        currentNode = currentNode->next;
    }
}

可以简化为:

Linked_List::Linked_List(const Linked_List & obj)
   : head(nullptr)
{
    Node * currentNode = obj.head;
    Node ** newNode = &head;

    while (currentNode)
    {
        *newNode = new Node;
        (*newNode)->character = currentNode->character;
        newNode = &(newNode->next);
        currentNode = currentNode->next;
    }
}

关于c++ - 链表的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256529/

相关文章:

c++ - 错误: redefinition of function template (or C2995)

c++ - QCustomPlot 和 iRangeDrag 在第二个右边的 yAxis

c# - 在 Linux X11/Gtk 上创建分层窗口

c++ - 如何使每个线数组中的颜色发生变化 C++

c++ - 从 .obj 文件在 OpenGL 中绘制四边形

c++ - C++/OpenSSL将PEM加载到STACK_OF(X509)

c++ - 如何转发声明在未命名命名空间中的类

c++ - 动态和经典多维数组的速度差异

c++ - 对 std::numeric_limits<double>::digits10 的误解

c++ - std::vector 的容量如何自动增长?费率是多少?