#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 50 //定义栈中元素最大个数
typedef struct {
int data[MaxSize]; //存放栈中元素
int top; //栈顶指针
}SqStack;
// 顺序栈的初始化
void InitStack(SqStack *S)
{
(*S).top = -1;
return true;
}
//判断栈是否为空
bool StackEmpty(SqStack *S)
{
if((*S).top == -1)
{
printf("当前栈为空\n");
return true;//栈空
}
else
{
printf("当前栈非空\n");
return false;//栈非空
}
}
//进栈
bool Push(SqStack *S, int e)
{
if ((*S).top == MaxSize - 1)
{
return false;
}
else
{
(*S).data[++(*S).top] = e;
return true;
}
}
//出栈
bool Pop(SqStack *S, int *e)
{
if ((*S).top == - 1)
{
return false;
}
else
{
(*e) = (*S).data[(*S).top--];
return true;
}
}
//读栈顶元素
bool GetTop(SqStack *S, int *e)
{
if ((*S).top == - 1)
{
return false;
}
else
{
(*e) = (*S).data[(*S).top];
return true;
}
}
int main()
{
SqStack S1;
int e = -1;
InitStack(&S1);
StackEmpty(&S1);
Push(&S1, 1);
Push(&S1, 2);
Push(&S1, 3);
Push(&S1, 4);
Push(&S1, 5);
Push(&S1, 6);
Push(&S1, 7);
Push(&S1, 8);
GetTop(&S1, &e);
printf("栈顶元素为%d\n", e);
Pop(&S1, &e);
GetTop(&S1, &e);
printf("栈顶元素为%d\n", e);
return 0;
}
07-24
864
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-01