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 - 返回地址和返回指针的区别

c++ - 如何清理(析构函数)动态指针数组?

将二进制链表转换为等效的十进制数

创建链表+添加新节点+打印列表,但无法弄清楚为什么它不起作用

c - 链表头部动态分配——C

c++ - Qt:将事件发布到 QThread 的正确方法?

c++ - OpenGL 三角形 strip 上不需要的颜色褪色问题。想要在三角形上获得统一的颜色

c++ - 从 8 位字节中提取二进制数据并将其转换为原始类型 [C++]

Char指针存放int类型数据的地址