从堆栈中删除数字


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<<"nnList Is:n";
        while(pointerFunc3)
        {
            cout<<pointerFunc3->number<<endl;
            pointerFunc3=pointerFunc3->next_number;
        }
    }
}

类的构造函数

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

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

Stack遵循后进先出策略。您可以删除/弹出您推送到堆栈的最后一个数字。要做到这一点,您的pop必须像这样:

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<<"nnList Is:n";
    while(pointer)
    {
        std::cout<<pointer->number<<std::endl;
        pointer=pointer->next_number;
    }
}}

catch that i found:

  1. 您从未在类中声明tailPointer,而是使用频繁。
  2. popNumber函数不返回任何值
  3. 请发布推送功能也可能是错误在那里

相关内容

  • 没有找到相关文章

最新更新