#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAXLIE 100
typedef int DataType;
typedef struct { //顺序栈存储类型
DataType data[MAXLIE]; //存放顺序栈的数组
int top; //栈顶元素的位置
}SqStack;
void InitStack(SqStack* S) {
S->top = -1; //初始化栈顶指针为空
}
int EmptyStack(SqStack *S) {
if (S->top == -1) //判断栈是否为空
return 1;
else
return 0;
}
int FullStack(SqStack* S) {
if (S->top == MAXLIE - 1) //栈是否满
return 1;
else
return 0;
}
int Push(SqStack* S, DataType x) {
if (FullStack(S)) { //调用FullStack(S)函数,判断栈是否满
printf("栈已满,不能进!");
return 0;
}
else {
S->top++;
S->data[S->top] = x;
return 1;
}
}
int Pop(SqStack *S, DataType *x) {
if (EmptyStack(S)) { //调用EmptyStack(S)函数,判断栈是否为空
printf("栈为空,出不了!");
return 0;
}
else {
*x = S->data[S->top];
S->top--;
return 1;
}
}
int GetStack(SqStack* S, DataType* x) {
if (EmptyStack(S)) { //调用EmptyStack(S)函数,判断栈是否为空
printf("栈为空,取不了!");
return 0;
}
else {
*x = S->data[S->top];
return 1;
}
}
int main() {
SqStack S;
DataType x;
int i,n;
InitStack(&S);//初始化栈
EmptyStack(&S);//判断栈空
FullStack(&S);//判断栈满
printf("请输入要进栈的元素个数:");
scanf("%d", &n);
printf("请输入%d个整数:", n);
for (i = 0; i < n; i++) {
scanf("%d", &x);
Push(&S, x);//进栈
}
printf("请输入要出栈的元素个数:");
scanf("%d", &n);
printf("请输入出栈的元素:");
for (i = 0; i < n; i++) {
scanf("%d", &x);
Pop(&S, &x);//出栈
}
GetStack(&S, &x);//取栈顶元素
printf("栈顶元素为:%d",x);
return 0;
}
顺序栈的基本操作实现
最新推荐文章于 2024-07-25 11:27:31 发布