链表删除和复制

Linked list deletion and duplication

本文关键字:复制 删除 链表      更新时间:2023-10-16

在代码中我将newnode复制到head节点,也复制到temp节点。但是当我删除一个数据实例时,它似乎也会影响到其他位置。当我释放newnode时,它也擦除了headtemp的内容。这是怎么发生的?

虽然我最初复制了数据,但数据被释放了。这是由于去引用?那么,如果我想要一个复制列表并且想要在不影响原始列表的情况下对其进行操作,我该怎么做呢?

我最初通过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);
}