链接列表删除和复制

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

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

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

 #include  #include  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<data; head=head->next; } cout<data; free(newnode); free(head); cout<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); }