原理:利用栈底位置相对不变的特性,让两个顺序栈共享一个一维数组空间,将两个栈的栈底分别设置在一维数组的两端,两个栈顶向中间延申。
#include<stdio.h>
#define MaxSize 10
typedef struct {
int data[MaxSize];
int top0,top1;//分别是0号栈和1号栈的栈顶指针
}ShStack;
//初始化,指向的是栈顶元素
void InitStack(ShStack &s){
s.top0 = -1;
s.top1 = MaxSize;
}
//销毁0号栈
void DestoryStackZero(ShStack &s){
s.top0 = -1;
}
//销毁1号栈
void DestoryStackOne(ShStack &s){
s.top1 = MaxSize;
}
//入0号栈
bool PushZore(ShStack &s,int x){
if(s.top0+1==s.top1)return false;//判断栈满
s.data[++s.top0] = x;
return true;
}
//入1号栈
bool PushOne(ShStack &s,int x){
if(s.top1-1==s.top0)return false;//判断栈满
s.data[--s.top1] = x;
return true;
}
//出0号栈
bool PopZero(ShStack &s,int &x){
if(s.top0==-1)return false;
x = s.data[s.top0--];
return true;
}
//出1号栈
bool PopOne(ShStack &s,int &x){
if(s.top1==MaxSize)return false;
x = s.data[s.top0++];
return true;
}
//查询栈顶元素,每一栈单看都与一个普通的线性栈相同
bool GetTopOne(ShStack s,int &x){
if(s.top1==MaxSize)return false;
x = s.data[s.top1];
return true;
}
//void Print(ShStack &s){
// for (int i = 0; i < MaxSize; i++) {
// printf("%d ",s.data[i]);
// }
// printf("\n");
//}
int main(){
ShStack s;
InitStack(s);
PushOne(s,1);
PushZore(s,999);
int x0,x1;
GetTopOne(s,x1);
printf("%d\n",x1);
//Print(s);
PopOne(s,x0);
printf("%d\n",x0);
PopZero(s,x0);
printf("%d\n",x0);
return 0;
}