【问题标题】:popping out a number from a stack list (linked list)?从堆栈列表(链表)中弹出一个数字?
【发布时间】:2013-03-26 03:37:32
【问题描述】:
class stack_class
{
private:

    struct stack_struct *head;

public:
    stack_class();
    ~stack_class();
    void pushNumber(int number);
    void popNumber();
    void findNumber();
    void clearStack();
    void sizeFinder();
    void printStack();

};

void stack_class::popNumber()
{
    stack_struct *pointerPop=NULL,*pointerPop2=NULL;
    int popCounter=0,i=0;
    pointerPop2=tailPointer;
    if(head==NULL)
    {
        cout<<"\nNo Member to Delete.\n";
    }
    else
    {
        while(pointerPop2)
        {
            popCounter++;
            //cout<<pointerFunc3->number<<endl;
            pointerPop2=pointerPop2->next_number;
        }
        pointerPop=tailPointer;
        while(i<(popCounter-2))
        {
            pointerPop=pointerPop->next_number;
            i++;
        }
        pointerPop->next_number=NULL;
        delete head;
        head=pointerPop;
    }

}

void stack_class::printStack()
{
    pointerFunc3=tailPointer;
    if(tailPointer==NULL)
    {
        cout<<"\nNo Members in List.\n";
    }
    else
    {
        cout<<"\n\nList Is:\n";
        while(pointerFunc3)
        {
            cout<<pointerFunc3->number<<endl;
            pointerFunc3=pointerFunc3->next_number;
        }
    }

}

类的构造函数

stack_class::stack_class()
{
    head=NULL;
}

这是我的代码,问题是,当我弹出最后一个数字并尝试打印列表时,它会进入无限循环并打印垃圾。当我在列表中的所有内容都被删除后按下删除选项时,程序会冻结。有什么建议为什么会这样??我该如何解决?

【问题讨论】:

  • 你的类实现了构造函数吗?
  • @AlexB 是的,有一个构造函数和一个析构函数。如果有帮助,我会添加它。

标签: c++ class linked-list


【解决方案1】:

第一个 while 循环的条件永远不会为假。根据您实现 next_number 的方式(如果它是循环链表),我相信您应该将其更改为:

while(pointerPop2 != head)

如果你想让它遍历所有节点。

【讨论】:

  • 实际上循环遍历了整个事情,我遇到的问题是当最后一个节点被删除时,程序打印垃圾。
猜你喜欢
  • 2012-10-14
  • 2018-03-08
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多