当 i 从链表中删除元素后显示时,显示 0 代替已删除的元素。我在更新节点时遇到问题。谁能解释发生了什么?为什么显示0?
#include<iostream>
#include<stdlib.h>
using namespace std;
class node {
public:
int data;
node *link;
};
class linkedlist {
node *head;
public:
linkedlist() {
head=NULL;
}
int add(int data1) {
node *insertnode=new node;
insertnode->data=data1;
insertnode->link=NULL;
node *temp=head;
if(temp!=NULL)
{
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=insertnode;
}
else{head=insertnode;}
}
void disp()
{
node *temp1=head;
cout<<endl;
if(temp1==NULL)
{
cout<<"Empty"<<endl;
}
if(temp1->link==NULL)
{
cout<<temp1->data<<endl;
}
else {
do {
cout<<temp1->data<<endl;
temp1=temp1->link;
} while(temp1!=NULL);
}
}
int remove(int removedata)
{
node *previous;
node *temp2=head;
if(temp2==NULL)
{exit(0);}
if(temp2->link==NULL)
{
delete temp2;
head=NULL;
}
else
{
while(temp2!=NULL)
{
if(temp2->data==removedata)
{
previous=temp2;
delete temp2;
}
temp2=temp2->link;
}
}
}
};
int main()
{
linkedlist list;
list.add(10);
list.add(100);
list.add(200);
list.remove(10);
list.disp();
}
显示的输出是:
0
100
200