从堆栈中删除数字?

时间:2013-03-26 03:59:55

标签: c++ class linked-list stack

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

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

1 个答案:

答案 0 :(得分:1)

Stack意味着遵循后进先出政策。您可以删除/弹出已推送到堆栈的最后一个号码。为此,你的流行音乐必须是这样的:

int stack_class::popNumber(){
stack_struct *pointerPop=NULL; //,*pointerPop2=NULL; //not needed
int number; //number poped
//int popCounter=0,i=0;
//pointerPop2=tailPointer;
if(head==NULL)
{
    std::cout<<"\nNo Member to POP.\n";
}
else
{
    pointerPop = head;
    number = head->number;
    delete head;
    head = pointerPop;
    return number;//control ended

    //[[this part is not neccessary
    while(pointerPop2)
    {
        popCounter++;
        //std::cout<<pointerFunc3->number<<std::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(){
stack_struct *pointer = head;
if(head == NULL)
{
    std::cout<<"\nNo Members in List.\n";
}
else
{
    std::cout<<"\n\nList Is:\n";
    while(pointer)
    {
        std::cout<<pointer->number<<std::endl;
        pointer=pointer->next_number;
    }
}}

我发现的捕获物:

  1. 你从未在课堂上宣布过tailPointer而是使用了 频繁。
  2. popNumber函数不返回任何内容。
  3. 请发布推送功能也可能是错误在那里