【问题标题】:C++ Pop Function Linked ListC++ Pop 函数链表
【发布时间】:2023-03-20 03:30:01
【问题描述】:

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

【问题讨论】:

  • 如果topPtrnullptr 或未初始化,就会发生这种情况。所以 1:您需要确保在构造函数中初始化 topPtr = nullptr; 和 2:您需要检查 Pop 上的堆栈深度(不能从空堆栈中弹出!)。
  • topPtr 未初始化!
  • 您希望topPtr 指向什么?

标签: c++ pointers linked-list stack


【解决方案1】:

首先,您不会初始化指针。

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.
    }
    ///...
}

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2014-07-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多