//顺序栈初始化,判栈空,进栈,读栈顶元素,出栈
include <stdio.h>
include <stdlib.h>
define MAXSIZE 50
typedef struct
{
int data[MAXSIZE]; //存放栈中元素
int top; //栈顶指针
} SqStack;
void InitStack(SqStack *S)
{
S->top = -1; //初始化栈顶指针
}
int StackEmpty(SqStack S)
{
if (S.top == -1) //栈空
{
printf("空栈。\n");
}
else //不空
{
printf("非空栈。\n");
}
return 0;
}
int Push(SqStack *S, int x)
{
if (S->top == MAXSIZE - 1) //栈满,报错
{
return 0;
}
else
{
S->data[++S->top] = x; //指针先加1,再入栈
}
return x;
}
int Pop(SqStack *S, int *x)
{
if (S->top == -1) //栈空,指针报错
{
printf("栈空。");
}
else
{
*x = S->data[S->top--]; //先出栈,指针再减1
printf("出栈元素为:%d\n", *x);
}
return *x;
}
int GetTop(SqStack S, int *x)
{
if (S.top == -1) //栈空,报错
{
printf("栈空。");
}
else
{
*x = S.data[S.top]; //x记录栈顶元素
printf("栈顶元素:%d\n", *x);
}
return *x;
}
int main()
{
SqStack S;
int x;
InitStack(&S);
StackEmpty(S);
Push(&S, 11);
GetTop(S, &x);
Pop(&S, &x);
Pop(&S, &x);
printf("\n");
return 0;
}
运行结果: