【发布时间】:2013-03-20 20:10:30
【问题描述】:
到目前为止我的代码是...
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;
}
}
}
只要不是最后一个数字,弹出就可以正常工作。如果弹出最后一个数字(列表为空),并且我尝试打印列表,程序会无限打印垃圾。如果我在列表为空后尝试弹出一个数字,程序会冻结。我该如何解决这些问题?
【问题讨论】:
-
你为什么到处使用全局变量?此外,您没有将
head设置为NULL的代码。请记住,设置指向NULL的指针不会改变指向同一事物的任何其他内容。 -
当弹出元素时,如果堆栈为空,则什么也不做。打印时,如果堆栈为空,您的代码不应打印任何内容(您应该能够判断是否是这种情况)
-
@Dave 我正在使用全局变量,因为我在程序中使用了开关。
-
...什么?你的意思是像
switch/case?这与全局无关。 -
@Dave 如果我使用本地变量,并且想在不同的开关情况下使用,编译器会说未在范围内声明。
标签: c++ linked-list stack