无法删除头部节点并从c ++

时间:2018-04-25 05:49:37

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

我想以相反的顺序打印列表,并逐个删除列表项,最后列表应为空。

我的输出不是必需的,所以在这种情况下:

我正在尝试在Head->temp函数中将temp分配给int returnRemoveHead()。 BUt,我无法提供Invalid conversion from int to NodePtr的错误。此外,L1.RemoveHead()函数中的main()甚至无效,而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;
    }
}   

1 个答案:

答案 0 :(得分: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;
    }
}