必备知识
栈(stack):只允许在一端进行插入或删除操作的线性表。先进后出,FILO。
元素入栈:S.data[++S.top]=x;
元素出栈:x=S.data[S.top–];
在进行入栈操作时,首先要检查栈是否满了,如果栈满,就不能进行入栈操作,如果栈没满,可进行入栈操作。栈满条件为:S.top等于MaxSize-1;
同理,在进行出栈操作时,首先要检查栈是否为空,如果栈为空,就不能进行出栈操作,如果栈不为空,可进行出栈操作。栈为空的条件为:S.top等于-1;
代码编写思想
1.创建线性表
2.对线性表进行初始化
3.元素入栈
4.元素出栈
以下代码测试运行环境为visual studio-2019
//顺序存储实现栈
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct {
ElemType data[50];
int top;//栈顶
}SqStack;
void InitStack(SqStack& S) {
S.top = -1;//对线性表进行初始化,即新创建的线性表为空
}
bool IsEmpty(SqStack S) {
if (-1 == S.top) {
return true;//判断栈是否为空
}
return false;
}
bool IsFull(SqStack S) {
if (49 == S.top) {
return true;//判断栈是后满了
}
return false;
}
bool Push(SqStack& S, ElemType x) {
if (IsFull(S)) {//执行入栈操作前,先判断是否能入栈
return false;
}
S.data[++S.top] = x;//入栈操作
return true;
}
bool Pop(SqStack& S, ElemType& x) {
if (IsEmpty(S)) {//在执行出栈操作前,判断是否能执行出栈操作
return false;
}
x = S.data[S.top--];//出栈操作
return true;
}
int main() {
//1.创建一个线性表
SqStack S;
//2.对线性表进行初始化
InitStack(S);
bool ret;
//3.元素入栈
ElemType n;
for (int i = 0; i < 3; i++) {
scanf("%d", &n);
Push(S, n);
}
//4.元素出栈
ElemType m;
for (int i = S.top; i > -1; i--) {
ret = Pop(S, m);
if (ret) {
printf("出栈元素为:%d\n", m);
}
}
return 0;
}