【发布时间】:2013-01-02 08:12:47
【问题描述】:
在下面的代码中,当我在删除第一个元素后尝试显示列表时,会导致下一个元素的无限循环。当除第一个元素被删除时,不会发生此问题。我不知道为什么会这样?谁能告诉我错在哪里?
#include<iostream>
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 *temp2=head;
if(temp2==NULL)
{}
if(temp2->link==NULL)
{
delete temp2;
head=NULL;
}
else
{
node *previous;
do
{
if(temp2->data==removedata) break;
previous=temp2;
temp2=temp2->link;
}while(temp2!=NULL);
previous->link=temp2->link;
delete temp2;
}
}
};
int main()
{
linkedlist list;
list.add(10);
list.add(100);
list.add(200);
list.remove(10);
list.disp();
}
谢谢大家。问题已经解决了
【问题讨论】:
-
请向我们显示输出如果列表中有一个循环,这种行为是预期的 - 如果没有一些额外的工作,您无法真正知道列表何时结束
-
你试过调试它吗?
-
if(temp2==NULL) {}??? -
第一次插入时会发生什么(head Is NULL)?
-
删除第一个元素后,循环后
previous和temp2的值是多少?删除后head的值是多少? (铅笔和纸是这里最好的调试工具。)