栈的应用篇2:共享栈的应用
描述:本篇为共享栈的另一应用,试想如何能提高栈的空间利用率,共享栈便不失为一个好的想法,两个栈共享一个内存空间,动态操作数据,以下为具体过程:
基本设计思想:
顺序栈的栈底固定不动,我们将其设置在存储区的两端,假设s0为0处,s1设置在maxSize-1处,栈顶在0~maxSize-1活动,当两栈栈顶相遇便为栈满;s0的栈顶为top[0],进栈时规定先自增,再存入元素,出栈时先取元素,指针再自减1;s1入栈时top先自减,再存入元素,出栈时先取元素,指针再自增1。
#include<stdio.h>
#include <iostream>
using namespace std;
#define MAXSIZE 100
//定义栈的结构体
typedef struct
{
//栈的数据
int data[MAXSIZE];
//top[0],top[1]分别表示栈1和栈2的栈顶坐标
int top[2];
}Sqstack;
//入栈操作
int push(Sqstack &st,int stNo,int x) //stNo为栈编号
{
if(top[0]+1 < top[1])//栈不满,元素入栈
{
if(stNo == 0)
{
++(st.top[0]);
st.data[st.top[0]]=x;
return 1; //入栈成功
}
else if(stNo == 1)
{
--(st.top[1]);
st.data[st.top[1]]=x;
return 1; //入栈成功
}
else return -1;
}
else return 0; //栈满后元素不能入栈
}
//出栈操作
int pop(Sqstack &st,int stNo,int &x) //stNo为栈编号
{
if(stNo == 0)//st0元素入栈
{
if(st.top[0] != -1)
{
x = st.data[st.top[0]];
--(st.top[0]);
return 1; //出栈成功
}
else return 0; //st0栈空,出栈失败
}
else if(stNo == 1)
{
if(st.top[1] != MAXSIZE) //st1不空,可以出栈
{
x = st.data[st.top[1]];
++(st.top[1]);
return 1; //出栈成功
}
else return 0; //s0栈空,出栈失败
}
else return -1;
}