顺序栈的定义
#define MaxSize 50
#define bool int
#define true 1
#define false 0;
typedef struct
{
int top;
int data[MaxSize];
}SqStack;
判断栈空
bool IsEmpty(SqStack S)
{
if(S.top==-1)
return true;
else
return false;
}
判断栈满
bool IsFull(SqStack S)
{
if(S.top==MaxSize-1)
return true;
else
return false;
}
初始化栈
void InitStack(SqStack *S)
{
S->top=-1;
}
创建栈
bool CreateStack(SqStack *S)
{
if(IsFull(*S)) return false;
int data;
printf("请输入整数:");
scanf("%d",&data);
while(data!=9999&&!IsFull(*S))
{
S->top++;
S->data[S->top]=data;
printf("请输入整数:");
scanf("%d",&data);
}
return true;
}
输出栈
void PrintStack(SqStack S)
{
for (int i=0; i<=S.top; i++) {
printf("S.data[%d]=%d\n",i,S.data[i]);
}
}
压栈
bool PushStack(SqStack *S,int e)
{
if(IsFull(*S))return false;
S->top++;
S->data[S->top]=e;
return true;
}
退栈
bool PopStack(SqStack *S,int *e)
{
if(IsEmpty(*S))return false;
*e=S->data[S->top];
S->top--;
return true;
}
获取栈顶元素
int GetTopStack(SqStack S)
{
if(!IsEmpty(S))
return S.data[S.top];
return -1;
}
测试代码
int main(int argc, const char * argv[]) {
SqStack S;
InitStack(&S);
CreateStack(&S);
PrintStack(S);
printf("GetTopStack(S)=%d\n",GetTopStack(S));
printf("PushStack(&S,606)\n");
PushStack(&S,606);
PrintStack(S);
int *e;
PopStack(&S, &e);
printf("PopStack(&S, &e)=%d\n",*e);
PrintStack(S);
return 0;
}
测试结果
请输入整数:11
请输入整数:12
请输入整数:13
请输入整数:9999
S.data[0]=11
S.data[1]=12
S.data[2]=13
GetTopStack(S)=13
PushStack(&S,606)
S.data[0]=11
S.data[1]=12
S.data[2]=13
S.data[3]=606
S->data[S->top]=606PopStack(&S, &e)=1068761088
S.data[0]=11
S.data[1]=12
S.data[2]=13
Program ended with exit code: 0