C++ C++;Pop函数链表
我正在编写一个程序,将堆栈实现为链表。程序符合要求,但当我运行它时,它崩溃了。我运行了调试器,当它进入Pop()函数并到达“topttr=topttr->next”行时,会说未处理的异常。我想知道是否有人注意到了导致这个错误的东西。我附加了main和pop函数的一部分,我认为我受到了影响。谢谢C++ C++;Pop函数链表,c++,pointers,linked-list,stack,C++,Pointers,Linked List,Stack,我正在编写一个程序,将堆栈实现为链表。程序符合要求,但当我运行它时,它崩溃了。我运行了调试器,当它进入Pop()函数并到达“topttr=topttr->next”行时,会说未处理的异常。我想知道是否有人注意到了导致这个错误的东西。我附加了main和pop函数的一部分,我认为我受到了影响。谢谢 template<class ItemType> struct NodeType { ItemType info; NodeType* next; }; template<
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);
}
模板
结构节点类型
{
项目类型信息;
NodeType*下一步;
};
模板
类堆栈
{
私人:
整数堆栈长度;
NodeType*topttr;//它指向一个单链接列表
公众:
作废Pop(项目类型和x);
模板
void Stack::Pop(ItemType&x)
{
节点类型*temptr;
tempPtr=topPtr;
topPtr=topPtr->next;
删除temptr;
堆栈长度--;
}
int main()
{
Stack-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
//...
如果
topttr
为nullptr
或未初始化,则会发生这种情况。因此1:您需要确保在构造函数中初始化topttr=nullptr;
,2:您需要检查Pop
上的堆栈深度(不能从空堆栈中弹出!).topttr
未初始化!您希望topttr
指向什么?
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.
}
///...
}