// // Created by kim on 2020/6/28. // //共享顺序栈的实现 //简单来说就是两个栈共享一片存储空间,提高顺序栈的对存储空间的使用率 #include # define MaxSize 10 typedef struct { int data[MaxSize]; int top0; int top1; } ShStack; //从结构体的定义就可以看出来,两个共享栈的根源就在于定义两个指针 //初始化 void InitStack(ShStack &S) { S.top0 = -1;//这种初始化的方式,栈顶指针始终指向栈顶元素 S.top1 =MaxSize;//这里的MaxSize就是所谓的第二个栈的栈底 //可以根据顺序栈的第二种初试化方式,思考一下这种共享顺序栈的第二种初始化方式 //S.top0=0 //S.top1=MaxSize-1 } //入栈0 bool Push0(ShStack &S, int t) { if (S.top0 +1== S.top1)return false;//注意共享栈满的条件 S.data[++S.top0] = t;//仔细品味一下这个++S.top return true; } //入栈1 bool Push1(ShStack &S, int t) { if (S.top0 +1== S.top1)return false;//注意共享栈满的条件 S.data[--S.top1] = t;//仔细品味一下这个--S.top,想想为什么? return true; } //出栈,并打印出栈顶元素 bool Pop0(ShStack &S, int &x) { //判断 if (S.top0 == -1)return false;//栈空报错 x = S.data[S.top0--]; // 等价于下面 // x=S.data[S.top];//先取元素 // S.top -=1;//再改指针 return true; } //出栈1 bool Pop1(ShStack &S, int &x) { //判断 if (S.top1 == MaxSize)return false;//注意一下它的栈空报错条件 x = S.data[S.top1++];//注意这个栈修改指针是++ // 等价于下面 // x=S.data[S.top];//先取元素 // S.top +=1;//再改指针 return true; } //读取栈顶元素,栈0 bool GetTop0(ShStack S, int &x) { if (S.top0 == -1)return false; x = S.data[S.top0]; return true; } //栈1 bool GetTop1(ShStack S, int &x) { if (S.top1 == MaxSize)return false; x = S.data[S.top1]; return true; } //打印整个栈,栈0 void PrintStack0(ShStack S){ printf("从栈顶元素开始,栈如下:\n"); while (S.top0>-1){//注意判空的条件 printf("S[%d]=%d\n",S.top0,S.data[S.top0--]); } printf("栈打印完毕\n"); } //打印整个栈 void PrintStack1(ShStack S){ printf("从栈顶元素开始,栈如下:\n"); while (S.top1