结构体中需要两个栈顶指针
一个从下至上存放
一个从上至下存放
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define maxsize 10
typedef struct {
int data[maxsize];
int top0; //0号栈栈顶指针
int top1; //1号栈栈顶指针
}ShStack;
//初始化栈
void InitStack(ShStack &s)
{
//初始化栈顶指针
s.top0=-1; //从下至上存放
s.top1=maxsize; //从上至下存放
}
//判空操作
bool emptystack(ShStack s)
{
if(s.top0==-1 && s.top1==maxsize)
return true;
else
return false;
}
//判满操作
bool fullstack(ShStack s)
{
if(s.top0==s.top1-1)
return true;
else
return false;
}
//往0号栈里存入元素
bool push0stack(ShStack &s,int x)
{
if(s.top0==s.top1-1) //栈满
return false;
s.top0++;
s.data[s.top0]=x;
return true;
}
//往1号栈里存入元素
bool push1stack(ShStack &s, int x)
{
if(s.top0==s.top1-1) //栈满
return false;
s.top1--;
s.data[s.top1]=x;
return true;
}
//从0号栈中弹出元素
bool pop0stack(ShStack &s, int &e)
{
if(s.top0==-1) //0号栈空
return false;
e=s.data[s.top0];
s.top0--;
return true;
}
//从1号栈中弹出元素
bool pop1stack(ShStack &s, int &e)
{
if(s.top1==maxsize) //1号栈空
return false;
e=s.data[s.top1];
s.top1++;
return true;
}
//读取0号栈顶的元素
bool gettop0(ShStack s)
{
if(s.top0==-1) //0号栈空
return false;
printf("%d\n",s.data[s.top0]);
return true;
}
//读取1号栈栈顶元素
bool gettop1(ShStack s)
{
if(s.top1==maxsize) //1号栈空
return false;
printf("%d\n",s.data[s.top1]);
return true;
}
int main()
{
ShStack s;
int e=0;
InitStack(s);
if (emptystack(s))
printf("栈空\n");
push0stack(s,999);
gettop0(s);
push1stack(s,99);
gettop1(s);
pop0stack(s,e);
printf("%d\n",e);
pop1stack(s,e);
printf("%d\n",e);
return 0;
}