C++ 无法从c+;中的列表中删除头节点和返回项+;
我想以相反的顺序打印列表,并逐个删除列表项,最后列表应该是空的 我的输出不符合要求,因此在这种情况下: 我正在尝试将C++ 无法从c+;中的列表中删除头节点和返回项+;,c++,class,data-structures,linked-list,C++,Class,Data Structures,Linked List,我想以相反的顺序打印列表,并逐个删除列表项,最后列表应该是空的 我的输出不符合要求,因此在这种情况下: 我正在尝试将Head->temp分配给tempint并在RemoveHead()函数中返回它。但是,我不能这样做,因为它给出了一个错误,从int到NodePtr的转换无效。另外,main()函数中的L1.RemoveHead()甚至不工作,L1.Print()没有打印“列表为空。”是int main()的最后一行 这是我的输出: ===== Testing Step-1 ===== Testi
Head->temp
分配给temp
int
并在RemoveHead()
函数中返回它。但是,我不能这样做,因为它给出了一个错误,从int到NodePtr的转换无效。另外,main()
函数中的L1.RemoveHead()
甚至不工作,L1.Print()
没有打印“列表为空。”
是int main()
的最后一行
这是我的输出:
===== 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()...
这应该是输出:
===== 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.
这是我的编程:
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();
while(!L1.IsEmpty())
cout << L1.RemoveHead()<< ' ';
cout << endl;
L1.Print();
}
void LinkedList::AddHead(int Item)
{
NodePtr newnode;
newnode = new Node;
newnode->Item = Item;
newnode->Next = Head;
Head = newnode;
}
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 temp;
}
}
bool LinkedList::IsEmpty()
{
return Head==NULL;
}
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;
}
}
intmain()
{
cout在LinkedList::RemoveHead()
中,删除后无法访问temp
NodePtr
指针指向的实例。您需要将整数结果保存到其他变量:
int LinkedList::RemoveHead()
{
if (! Head)
{
cerr << "Error Occured. " << endl;
exit(1);
}
else
{
int result = Head->Item;
NodePtr temp = Head;
Head = Head->Next;
delete temp;
return result;
}
}
int LinkedList::RemoveHead()
{
如果(!头)
{
cerr Next;
删除临时文件;
返回结果;
}
}
我们无法对我们不可用的类定义进行推理。请发布一个。设置指针可能有问题。能否添加LinkedList::AddHead()的源代码?刚刚添加。请看一看为什么在RemoveHead函数中临时存储Head和Head->item时使用相同的变量?NodePtr temp;temp=Head->item;
这是一个错误temp
是一个NodePtr
并分配给item
,它是一个int
。请使用不同的变量返回值