简体   繁体   English

使用带有链表的复制构造函数

[英]Using a copy constructor with a linked list

In my project I am trying to make it so I can make a copy of a linked list then display its contents. 在我的项目中,我试图制作它,以便我可以制作链表的副本,然后显示其内容。 Currently I have it working but every time I try to exit the program crashes. 目前我有它的工作,但每次我尝试退出程序崩溃。 I removed the instance of the copy constructor being used in the main part of the program so the problem seems to be coming from there. 我删除了程序主要部分中使用的复制构造函数的实例,所以问题似乎来自那里。 Here is the code: 这是代码:

struct ListNode{
    int num;
    struct ListNode *next;
};
ListNode *head;

List::List( const List& org){
   ListNode *copy=org.head;
   ListNode *temp;
   if(copy==NULL){
     head=NULL;
   }
   else{
     head=copy;
     while(copy!=NULL){
        temp=new ListNode;
        temp->num=copy->num;
        temp=temp->next;
        copy=copy->next;
     }
   }

}

Please note that I know that some of the brackets {} are a little off the program itself works up until I try to exit so I'm wonder how I would prevent the program from crashing? 请注意,我知道一些方括号{}有点偏离程序本身,直到我尝试退出,所以我想知道如何阻止程序崩溃?

Take a large sheet of paper, sketch a list to be copied (let's say with 4 nodes), and follow what must be done step by step. 拿一张大纸,勾勒出要复制的列表(假设有4个节点),并按照必须一步一步的步骤进行操作。 Then see how to translate that into code. 然后看看如何将其转换为代码。

The above code creates a bunch of disconnected nodes, not a list. 上面的代码创建了一堆断开连接的节点,而不是列表。

The newly created List has a head that points at the copied instance's head . 新创建的列表有一个head指向在复制的实例的head So if you delete those two list, you'll wind up trying to delete the same memory twice (I am assuming that your destructor does attempts to delete the nodes). 因此,如果删除这两个列表,您最终会尝试删除相同的内存两次(我假设您的析构函数尝试删除节点)。 By the way, the created nodes are allocated, but not referenced (ie. you have a memory leak). 顺便说一句,创建的节点是分配的,但没有被引用(即你有内存泄漏)。 You may want to look at Coding a function to copy a linked-list in C++ for some answers to a very similar question. 您可能希望查看编码函数以在C ++中复制链接列表,以获得一个非常相似的问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM