C++ Pop函数链表

标签 c++ pointers linked-list stack

我正在编写一个将堆栈实现为链表的程序。该程序符合要求,但是当我运行它时,它崩溃了。我运行了调试器,当它进入 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/

相关文章:

c++ - 元组和可变参数模板的编译问题

c - ANSI C : Passing array by value generates weird error I can not solve

c - 为什么声明 unsigned char "Volatile"会使其与 "non-volatile"unsigned char 不兼容?

c++ - C/C++ 动态链接如何在不同平台上工作?

C++ -- 需要重新编译时

c++ - 我应该预防性地 move 可调用对象(例如 lambda 吗?)

c - void **lineptr 和 (void** )lineptr 之间的区别

java链表复制构造函数

java - 在双向链表中创建自己的删除方法

c++ - 添加一个元素到链表的末尾