#define _CRT_SECURE_NO_WARNINGS//必须要放在第一行
#include <stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct {
ElemType data[MaxSize]; //静态数组存放栈中元素
int top0; //0号栈栈顶指针
int top1; //1号栈栈顶指针
}ShStack;
//初始化
void InitStack(ShStack& S) {
S.top0 = -1; //初始化栈顶指针
S.top1 = MaxSize;
}
//0号栈判空
bool Stack0Empty(ShStack S) {
return (S.top1 == -1);
}
//1号栈判空
bool Stack1Empty(ShStack S) {
return (S.top1 == MaxSize);
}
//0号栈入栈
bool Push0(ShStack& S, ElemType x) {
if (S.top0 + 1 == S.top1) //栈满 报错
return false;
S.data[++S.top0] = x;
return true;
}
//1号栈入栈
bool Push1(ShStack& S, ElemType x) {
if (S.top0 + 1 == S.top1) //栈满 报错
return false;
S.data[--S.top1] = x;
return true;
}
//0号栈弹栈
bool Pop0(ShStack& S, ElemType& x) {
if (Stack0Empty(S)) {
x = S.data[S.top0--];
return true;
}
return false;
}
//1号栈弹栈
bool Pop1(ShStack& S, ElemType& x) {
if (Stack1Empty(S)) {
x = S.data[S.top1++];
return true;
}
return false;
}
//0号栈读取栈顶元素
bool GetTop0(ShStack S, ElemType& x) {
if (Stack0Empty(S)) {
x = S.data[S.top0];
return true;
}
return false;
}
//1号栈读取栈顶元素
bool GetTop1(ShStack& S, ElemType& x) {
if (Stack1Empty(S)) {
x = S.data[S.top1];
return true;
}
return false;
}
int main() {
ShStack S;
bool flag;
ElemType x; //存储拿出来的栈顶元素
InitStack(S);
Push0(S, 3); Push0(S, 6); Push0(S, 4);
Push1(S, 5); Push1(S, 9); Push1(S, 8);
if(flag=GetTop0(S,x))
printf("获取0号栈顶元素为%d\n", x);
if (flag = GetTop1(S, x))
printf("获取1号栈顶元素为%d\n", x);
if (flag = Pop0(S, x))
printf("弹出元素为%d\n", x);
if (flag = Pop1(S, x))
printf("弹出元素为%d\n", x);
return 0;
}
共享栈---增删查
最新推荐文章于 2024-09-13 21:36:15 发布