链接列表删除和复制

时间:2015-06-06 13:35:23

标签: c++ c linked-list

在代码中,我将newnode复制到head节点,并复制到temp节点。但是当我删除数据实例时,它似乎也会影响其他位置。当我释放newnode时,它也会删除headtemp的内容。这种情况如何发生?

虽然我最初复制数据,但数据已被释放。这是由于解除引用?那么,如果我想要一个副本列表并希望在不影响原件的情况下操纵它,我该怎么办?

我最初通过malloc()来设置我想要的内存,但在以后的复制操作中,我看到代码不是malloc()而是只是复制了。它是如何工作的呢?我的两个问题有关系吗?

#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;
}

1 个答案:

答案 0 :(得分:1)

使用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);
}