C++弹出函数链表

C++ Pop Function Linked List

本文关键字:链表 函数 C++      更新时间:2023-10-16

我正在编写一个将堆栈实现为链表的程序。程序符合要求,但当我运行它时,它会崩溃。我运行了调试器,当它进入Pop()函数并到达"topPtr=topPtr->next"行时,我会说未处理的异常。我想知道是否有人注意到里面有什么东西导致了这个错误。我附上了我认为我受到影响的主要部分和流行功能。感谢

template<class ItemType>
struct NodeType
{ 
   ItemType info;
   NodeType* next;
};
template<class ItemType>
class Stack
{ 
private:
   int stacklength;
   NodeType<ItemType>* topPtr; // It points to a singly-linked list
public: 
    void Pop(ItemType &x);
template<class ItemType>
void Stack<ItemType>::Pop(ItemType &x)
{
    NodeType<ItemType>* tempPtr;
    tempPtr = topPtr;
    topPtr = topPtr->next;
    delete tempPtr;
    stacklength--;
}
int main()
{
Stack <int> IntStack;
int x;
IntStack.Pop(x);
}

首先,您不初始化指针。

template<class ItemType>
struct NodeType
{ 
    //...
    NodeType() : next(nullptr) {} ///Initialize next so we can check for null
};
template<class ItemType>
class Stack
{ 
public:
    Stack() : topPtr(nullptr), stacklength(0) { } ///initialize
    //...

然后,在Pop中,您需要检查是否有空堆栈(如果没有元素,则不能弹出)。

template<class ItemType>
void Stack<ItemType>::Pop(ItemType &x)
{
    if (!topPtr)
    {
        //Here, we need to decide how to handle this.
        //One way would be to throw an exception,
        //another way would be to change the method signature
        //and return a bool.
    }
    ///...
}