我正在编写一个将堆栈实现为链表的程序。该程序符合要求,但是当我运行它时,它崩溃了。我运行了调试器,当它进入 Pop() 函数内部并到达“topPtr = topPtr->next”行时,出现未处理的异常。我想知道是否有人注意到那里有什么东西导致了这个错误。我附上了我认为受到影响的 main 和 pop 功能部分。谢谢
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.
}
///...
}
关于C++ Pop函数链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052152/