链表删除和复制
Linked list deletion and duplication
在代码中我将newnode
复制到head
节点,也复制到temp
节点。但是当我删除一个数据实例时,它似乎也会影响到其他位置。当我释放newnode
时,它也擦除了head
和temp
的内容。这是怎么发生的?
虽然我最初复制了数据,但数据被释放了。这是由于去引用?那么,如果我想要一个复制列表并且想要在不影响原始列表的情况下对其进行操作,我该怎么做呢?
我最初通过malloc()
malloc了我想要的内存,但在后来的复制操作中,我看到代码不是malloc()
'ed而只是复制。它怎么还能正常工作?我的两个问题有关系吗?
#include <iostream>
#include <cstdlib>
using namespace std;
struct node{
int data;
struct node*next;
};
int main()
{
struct node*newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=2;
newnode->next=NULL;
struct node*head=NULL;
head=newnode;
struct node*temp=newnode;
while(head!=NULL)
{
cout<<head->data;
head=head->next;
}
cout<<temp->data;
free(newnode);
free(head);
cout<<temp->data;
return 0;
}
使用struct node *newnode=(struct node*)malloc(sizeof(struct node));
,您为一个节点分配一块内存,然后将该内存的地址分配给所有其他节点指针。因此,当您释放这部分内存时,该节点对任何节点指针都不再可用。
struct node *head=newnode; // head now points to *newnode
struct node *temp=newnode; // temp now also points to *newnode
...
free(newnode); // newnode, head and temp point to released memory now
free(head); // oops! head was released already by the previous statement
注意:这是C的解释。在c++中,类的构造函数可以分配内存,重新定义的赋值操作符可以创建对象的新实例(但我不是c++程序员)。
下面的函数创建列表的副本:
struct node *copylist(struct node *oldlist)
{
struct node *newhead, *list;
if (!oldlist) return(0);
list= newhead= malloc(sizeof(struct node));
*newhead= *oldlist;
while (oldlist->next) {
list->next= malloc(sizeof(struct node));
oldlist= oldlist->next;
list= list->next;
*list= *oldlist;
}
list->next= NULL;
return(newhead);
}
相关文章:
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- std::ofstream 作为类成员删除复制构造函数?
- 具有已删除移动和复制构造函数的类的就地构造
- 聚合初始化和删除的复制构造函数,也称为不可复制的 obejcts 作为字段
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 在引用初始化中使用已删除的复制构造函数进行复制初始化
- std::p ackaged_task 应该删除带有 const 参数的复制 c'tor
- 我什么时候会默认(而不是删除)基类中的复制和移动操作
- 为什么在删除"移动构造函数"时使用"复制构造函数"?
- 调用类模板中隐式删除的复制构造函数
- 为什么基类中的复制和交换会导致派生类中的复制赋值运算符被隐式删除?
- shared_ptr删除器类 - 为什么要复制删除器?
- 复制后删除原始数组指针将前 3 个字节设置为 0
- 删除复制构造函数的 Intel 13.1.2 中不良C++行为的解决方法
- c++:复制、删除和运算符=在原始指针映射中
- c++17在编译时将带有已删除复制构造函数的类添加到std::vector
- Windows Portable设备 - 创建 /复制 /删除新文件时通知
- 复制-删除返回的自动变量
- 列表初始化和复制删除