我希望我的程序删除节点并返回RemoveHead()
函数中的项目。我不确定这是什么错误。在main()
函数中,一切正常,但我的程序没有删除Head
,它仍然打印上一个列表L1
:非空列表。
为了更清楚,我正在上传我的输出和所需的输出。
这是我的计划:
int main()
{
cout << "===== Testing Step-1 =====\n";
cout << "Testing default constructor...\n";
LinkedList L1;
L1.Print(); // should be empty
cout<<"\nTesting AddHead()...\n";
for(int i=0; i<10; i++){
cout << i << ' ';
L1.AddHead(i);
}
cout << endl;
L1.Print();
cout << "\nTesting IsEmpty() and RemoveHead()...\n";
while(!L1.IsEmpty())
cout << L1.RemoveHead()<< ' '; // should be printed in reverse
cout << endl;
L1.Print(); // should be empty
}
int LinkedList::RemoveHead()
{
if(Head==NULL)
{
cerr << "Error Occured. " << endl;
exit(1);
}
else
{
NodePtr temp;
temp->Item = Head->Item;
temp = Head;
Head = Head->Next;
delete temp;
}
//return 0; to be removed while compilation
bool LinkedList::IsEmpty()
{
Head==NULL;
return true;
}
void LinkedList::Print()
{
if (Head==0)
{
cout << "Empty error ." ;
}
else
{
NodePtr crnt;
crnt = Head;
while(crnt!= NULL)
{
cout << crnt->Item << " ";
crnt = crnt->Next;
}
cout << endl;
}
}
我的输出应该是这样的:
===== Testing Step-1 =====
Testing default constructor...
List is empty.
Testing AddHead()...
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
Testing IsEmpty() and RemoveHead()...
9 8 7 6 5 4 3 2 1 0
List is empty.
答案 0 :(得分:1)
正如Johnny Mopp的评论所述:
您的IsEmpty()
方法应该重构:
bool LinkedList::IsEmpty()
{
Head==NULL;
return true;
}
对此:
bool LinkedList::IsEmpty()
{
return Head==nullptr;
}