popping out a number from a stack list (linked list)?

人走茶凉 提交于 2019-12-13 20:24:48

问题


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;
        }
    }

}

constructor to class

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

This is my code, the problem with it is, when I POP the very last number and try to print the list, it enters an infinite loop and prints garbage. when I press the delete option after everything in the list has been deleted, the program freezes. Any suggestions why this is acting like this??And how do I fix it?


回答1:


The condition of your first while loop will never be false. Depending on how you've implemented your next_number (if it's a circular linked list), I believe you should change it to:

while(pointerPop2 != head)

if you want it to loop through all nodes.



来源:https://stackoverflow.com/questions/15628960/popping-out-a-number-from-a-stack-list-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!