【问题标题】:Unable to remove head node and returning items from the list in c++无法从 C++ 列表中删除头节点并返回项目
【发布时间】:2018-04-25 05:49:37
【问题描述】:

我想以相反的顺序打印列表,并一个一个地删除列表项,最后列表应该是空的。

我的输出不符合要求,所以在这种情况下:

我正在尝试将Head->temp 分配给temp intreturnRemoveHead() 函数中。但是,我不能,因为它给出的错误是Invalid conversion from int to NodePtr。此外,main() 函数中的L1.RemoveHead() 甚至无法正常工作,L1.Print() 没有打印"List is empty.",这是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;
    }
}   

【问题讨论】:

  • 我们无法推断我们无法使用的类定义。请发minimal reproducible example
  • 设置指针可能有问题。你能添加 LinkedList::AddHead() 的来源吗?
  • 刚刚添加。请看一下
  • 为什么在RemoveHead函数中使用同一个变量来临时存储Head和Head->item?
  • NodePtr temp; temp = Head-&gt;Item; 这是错误之一 tempNodePtr 并分配给 Item 这是 int。使用不同的变量返回值

标签: c++ class data-structures linked-list


【解决方案1】:

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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多