目录
1.题目描述
将编号为0和1的两个栈存放于一个数组空间V[m]中,栈底分别处于数组的两端。当第0号栈的栈顶指针top[0]等于-1时该栈为空;当第1号栈的栈顶指针top[1]等于m时该栈为空。两个栈均从两端向中间增长(见图)。试编写双栈初始化,判断栈空、栈满、进栈和出栈等算法的函数。
2.算法实现
#include<bits/stdc++.h>
#define MAXSIZE 100
using namespace std;
typedef struct
{
int top[2],bot[2]; //栈顶和栈底指针
int *V; //栈数组
int m; //栈最大可容纳元素个数
} DblStack;
int InitDblStack(DblStack &S)
{
S.V=new int [S.m];
S.m=MAXSIZE;
S.top[0]=-1;
S.top[1]=S.m;
return 1;
}
int isEmpty(DblStack &S)
{
if(S.top[0]==-1&&S.top[1]==S.m)
return 1;
else return 0;
}
int isFull(DblStack &S)
{
if(S.top[1]-S.top[0]==-1||S.top[1]<0||S.top[0]>S.m-1)
return 1;
else return 0;
}
int Push(DblStack &S,int i,int e)
{
//i为栈号,i为0表示左栈,i=1表示右栈,e是入栈元素。
if(i<0||i>1)
{
cout<<"栈号输入不对"<<endl;
exit(0);
}
if(S.top[1]-S.top[0]==1)
{
cout<<"栈已满!";
return 0;
}
switch(i)
{
case 0:
{
S.top[0]++;
S.V[S.top[0]]=e;
return 1;
break;
}
case 1:
{
S.V[S.top[1]]=e;
S.top[1]--;
return 1;
break;
}
}
}
int Pop(DblStack &S,int i)
{
/*退栈。i代表栈号,i=0为左栈,i=1为右栈
退栈成功时返回退栈元素*/
if(i<0||i>1)
{
cout<<"栈号输入不对"<<endl;
exit(0);
}
switch(i)
{
case 0:
if(S.top[0]==-1)
{
cout<<"栈空!";
return -1;
}
else return (S.V[S.top[0]]--);
case 1:
if(S.top[0]==S.m)
{
cout<<"栈空!";
return -1;
}
else return (S.V[S.top[1]]++);
}
}
void printDblStack(DblStack &S,int i)
{//遍历双栈,i为0遍历左栈,i为1遍历右栈
switch(i)
{
case 0:
{
for(int i=0;i<S.top[0];i++)
cout<<S.V[i]<<" ";
}
case 1:
{
for(int i=S.m;i<S.top[1];i--)
cout<<S.V[i]<<" ";
}
}
cout<<"\n";
}
void display()
{
cout<<" 1.双栈初始化!\n\n"
" 2.判断栈空!\n\n"
" 3.判断栈满!\n\n"
" 4.元素进栈!\n\n"
" 5.元素出栈!\n\n"
" 6.遍历双栈!\n\n"
" 0.退出!\n\n";
}
int main()
{
DblStack S;
int i,e;
bool a=true;
display();
while(a)
{
int n;
cout<<"请输入序号:";
cin>>n;
switch(n)
{
case 1:
{
if(InitDblStack(S))
cout<<"双栈初始化成功!\n\n";
break;
}
case 2:
{
if(isEmpty(S)) cout<<"栈空!\n\n";
else cout<<"栈非空!\n\n";
break;
}
case 3:
{
if(isFull(S)) cout<<"栈满!\n\n";
else cout<<"栈未满!\n\n";
break;
}
case 4:
{
cout<<"输入0进左栈,1进右栈:";
cin>>i;
cout<<"请输入进栈元素:";
cin>>e;
if(Push(S,i,e))cout<<"元素进栈成功!\n\n";
else cout<<"元素进栈成功!\n\n";
break;
}
case 5:
{
cout<<"输入0出左栈,1出右栈:";
cin>>i;
cout<<"出栈元素是:"<<Pop(S,i)<<"\n\n";
break;
}
case 6:
{
cout<<"输入0遍历左栈,1遍历右栈:";
cin>>i;
printDblStack(S,i);
break;
}
case 0:
{
a=false;
cout<<"已退出!\n\n";
break;
}
}
}
return 0;
}