问题:
将编号为0和1的两个栈存放于一个数组空间V[m]中,栈底分别处于数组的两端。当第0号栈的栈顶指针top[0]等于-1时该栈为空,当第1号栈的栈顶指针top[1]等于m时该栈为空。两个栈均从两端向中间增长。
试编写双栈初始化,判断栈空、栈满、进栈和出栈等算法的函数。
双栈数据结构的定义如下:
Typedef struct
{int top[2],bot[2]; //栈顶和栈底指针
SElemType *V; //栈数组
int m; //栈最大可容纳元素个数
}DblStack
#include<iostream>
using namespace std;
typedef struct
{
int top[2], bot[2]; //栈顶和栈底指针
int *v; //栈数组
int m; //栈最大可容纳元素个数
}DblStack;
void InitStack(DblStack &S)
{
S.top[0] = -1;
S.top[1] = S.m;
}
//判断栈空
bool IsEmptyStack(DblStack &S)
{
if (S.top[0] == -1 && S.top[1] == S.m)
return true;
else
return false;
}
//判断栈满
bool IsFullStack(DblStack &S)
{
if (!IsEmptyStack(S) && S.top[1]-S.top[0]==1)
return true;
else
return false;
}
//进栈
bool Push(DblStack &S,int rl,int e)
{//rl等于0进左栈,等于1进右栈
if (IsFullStack(S))
return false;
if (rl == 0)
{
S.bot[++S.top[0]] = e;
}
else if (rl == 1)
{
S.bot[--S.top[1]] = e;
}
return true;
}
//出栈
bool Pop(DblStack &S, int rl, int e)
{
if (IsEmptyStack(S))
return false;
if (rl == 0)
{
e = S.bot[S.top[0]--];
S.bot[++S.top[0]] = e;
}
else if (rl == 1)
{
S.bot[--S.top[1]] = e;
}
return true;
}