gpt4 book ai didi

c++ - 在 C++ 中从堆栈中弹出一个数字?

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:51 25 4
gpt4 key购买 nike

到目前为止我的代码是...

struct stack_struct
{
int number;
struct stack_struct *next_number;
};

stack_struct *mainStruct;

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 reverseStack();//Extra Credit
};
stack_class mainClassStack;

stack_struct *pointerFunc,*tailPointer=NULL,*pointerFunc3,*printPointer;

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

stack_class::~stack_class()
{
clearStack();
cout<<"\nList Cleared.\n";
system("pause");
}


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

}

只要不是最后一个数字,弹出就可以正常工作。如果弹出最后一个数字(列表为空),并且我尝试打印列表,程序会无限打印垃圾。如果我在列表为空后尝试弹出一个数字,程序会卡住。我该如何解决这些问题?

最佳答案

你也可以创建一个虚拟节点来解决这个问题。否则:



int stack_class::popNumber()
{
如果(头==空)
throw new Exception("堆栈为空");
int result = head->number;
删除头;
head = head->next_number;
返回结果;
}

void stack_class::pushNumber(整数)
{
stack_struct *elem= new stack_struct();
元素->数字=数字;
elem->next_number = head;
头=元素;
}

!!!!!尽量不要使用全局变量,例如 (stack_class mainClassStack;

stack_struct *pointerFunc,*tailPointer=NULL,)

关于c++ - 在 C++ 中从堆栈中弹出一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15714867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com