妳的判斷棧是否為空需要返回值,然後就好辦了。Pop的話用引用傳遞取回棧頂的值,所以沒用GetTop。
#include?<iostream>#include?<stdio.h>
#include?<malloc.h>
using?namespace?std;
#define?OK?1
#define?ERROR?0
#define?OVERFLOW?-2
#define?MAXSIZE?100
#define?exit
typedef?char?ElemType;
typedef?struct
{
ElemType?*base;//棧底指針
ElemType?*top;//棧頂指針
int?stacksize;//棧可用的最大容量
}?SqStack;
void?InitStack(SqStack?&S)
{
//構造壹個空棧S
S.base?=?new?ElemType[MAXSIZE];
if?(!S.base)
exit(OVERFLOW);
S.top?=?S.base;
S.stacksize?=?MAXSIZE;
}
bool?StackEmpty(SqStack?&S)?//判斷棧是否為空
{
if(S.top==S.base)
{
printf("順序棧為空\n");
return?true;
}
else
{
printf("順序棧為非空\n");
return?false;
}
}
bool?Push(SqStack?&S,ElemType?e?)//順序棧進棧
{
if(S.top-S.base==S.stacksize)
return?ERROR;
*S.top++=e;
return?OK;
}
bool?Pop(SqStack?&S,ElemType?&e)?//順序棧出棧
{
if(S.top==S.base)
return?ERROR;
e=*--S.top;
return?OK;
}
void?DestroyStack(SqStack?&S)?//銷毀
{
free(S.base);
printf("順序棧已銷毀");
}
bool?GetTop(SqStack?&S)?//取棧頂元素
{
if(S.top!=S.base)
return?*(S.top-1);
}
void?InitStack(SqStack?&S);
bool?StackEmpty(SqStack?&S);
bool?Push(SqStack?&S,ElemType?e?);
bool?Pop(SqStack?&S,ElemType?&e);
void?DestroyStack(SqStack?&S);
bool?GetTop(SqStack?&S,ElemType?&e);
int?main()
{
SqStack?S;
ElemType?e;
InitStack(S);
printf("順序棧已初始化\n");
StackEmpty(S);
Push(S,'a');
Push(S,'b');
Push(S,'c');
Push(S,'d');
Push(S,'e');
printf("已插入元素a,b,c,d,e,判斷棧是否為空?\n");
StackEmpty(S);
/***
將順序棧S棧內的
全部元素出棧,並
輸出出棧結果,求教!
***/
while(!StackEmpty(S))
{
ElemType?e;
Pop(S,?e);
printf("取出元素%c?\n",?e);
}
}