C++弹出函数链表
C++ Pop Function Linked List
我正在编写一个将堆栈实现为链表的程序。程序符合要求,但当我运行它时,它会崩溃。我运行了调试器,当它进入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.
}
///...
}
相关文章:
- 链表,反向函数,数据结构
- 链表的泛型函数remove()与成员函数remove)
- 链表中的 C++ 析构函数
- 为什么我的双向链表删除函数会删除多个节点?
- 在 c++ 中具有向量的双向链表构造函数
- C++析构函数被意外调用双链表
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 双链表的擦除值函数,未知错误
- 使用函数引用指向节点的指针删除链表中的节点?
- 使用析构函数释放链表
- 链表函数调用
- 使用链表函数循环
- 在C++中调用链表函数
- 链表函数出现问题
- 这个链表函数有什么问题?
- 链表函数 C++ "which is of non-class type 'int'" ?
- 链表函数 cpp 中的指针作用域
- 我的反向单向链表函数代码有什么问题?
- Delete_At链表函数使程序崩溃
- 双链表函数的一部分不能正常工作