编译环境:VS2019
直接上代码吧!
#define _CRT_SECURE_NO_WARNINGS //防止出现C4996错误
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 100
typedef struct Snode
{
int data[Maxsize];
int top;
}Seqstack;
//栈空: top = -1
//栈满: top = Maxsize - 1;
//栈中总元素个数: top + 1
//初始化栈
Seqstack* Init_Stack()
{
Seqstack* s;
//思考:此处为什么要用malloc开辟一段新的内存空间?
//因为s是指向结构体的指针,但现在连结构体都没有,所以要malloc一个和结构体大小相同的空间,使s指向它
s = (Seqstack*)malloc(sizeof(Seqstack));
s->top = -1;
return s;
}
//入栈
void Push_Stack(Seqstack* s, int e)
{
if (s->top == Maxsize - 1)
{
printf("FULL\n");
}
else
{
s->top++;
s->data[s->top] = e;
printf("PUSH!\n");
}
}
//出栈
int Pop_Stack(Seqstack* s)
{
int x;
if (s->top == -1)
{
printf("EMPTY!\n");
return 0; //表示函数正常终止
}
else
{
x = s->data[s->top];
printf("%d\n", x);
s->top--;
return 1; //表示函数非正常终止
}
}
//取栈顶元素
//此处注意取栈顶元素和出栈的区别
void Top_Pop(Seqstack* s)
{
if (s->top == -1)
{
printf("NULL\n");
return 1;
}
else
{
printf("%d\n", s->data[s->top]);
}
}
int main()
{
Seqstack* s;
s = Init_Stack();
Push_Stack(s, 3);//令3入栈
Push_Stack(s, 4);//令4入栈
Top_Pop(s); // 取栈顶元素
Pop_Stack(s);//出栈
Pop_Stack(s);//出栈
Pop_Stack(s);//出栈
return 0;
}