题目:将编号为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 <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
#define MAXSIZE 20
typedef int SElemType;
typedef struct
{
int top[2],bot[2];
SElemType *v;
int m;
}Dblstack;
void initstack(Dblstack &stack)
{
stack.m=MAXSIZE;
stack.bot[0]=stack.top[0]=-1;
stack.bot[1]=stack.top[1]=stack.m;
stack.v=new SElemType[MAXSIZE];
}
int emptystack(Dblstack stack,int no)
{
if(no==0 && stack.top[0]==-1)
return OK;
else if(no==1 && stack.top[1]==stack.m)
return OK;
else
return ERROR;
}
int fullstack(Dblstack stack)
{
if(stack.top[1]-stack.top[0]==1 &&(stack.top[0]!=-1 || stack.top[1]!=stack.m))
return OK;
else
return ERROR;
}
int pushstack(Dblstack &stack,int no,SElemType e)
{
if(fullstack(stack))
return ERROR;
if(no==0)
{
stack.top[0]++;
stack.v[stack.top[0]]=e;
}
else
{
stack.top[1]--;
stack.v[stack.top[1]]=e;
}
return OK;
}
int gettop(Dblstack &stack,int no,SElemType &e)
{
if(no==0)
e=stack.v[stack.top[no]];
else
e=stack.v[stack.top[no]];
return OK;
}
int popstack(Dblstack &stack,int no,SElemType e)
{
if(emptystack(stack,0) || emptystack(stack,1))
return ERROR;
if(no==0)
{
e=stack.v[stack.top[no]];
stack.v[stack.top[no]]=-1;
stack.top[no]--;
printf("%d,",e);
}
else
{
e=stack.v[stack.top[no]];
stack.v[stack.top[no]]=-1;
stack.top[no]++;
printf("%d,",e);
}
return OK;
}
int main()
{
Dblstack dblstack1;
initstack(dblstack1);
if(emptystack(dblstack1,0))
printf("0号栈目前为空!\n");
if(emptystack(dblstack1,1))
printf("1号栈目前为空!\n");
for(int i=1;i<12;i++)
{
if(!fullstack(dblstack1))
printf("插入元素:0号栈%3d,1号栈%3d\n",i,12-i);
pushstack(dblstack1,0,i);
pushstack(dblstack1,1,12-i);
}
if(fullstack(dblstack1))
printf("\n总栈已满!\n");
printf("\n0号栈出栈元素:");
for(int j=1;j<=8;j++)
popstack(dblstack1,0,j);
printf("\n\n1号栈出栈元素:");
for(int k=1;k<15;k++)
popstack(dblstack1,1,k);
if(emptystack(dblstack1,0))
printf("\n\n0号栈目前为空!\n");
else
printf("\n\n0号栈不为空!\n");
if(emptystack(dblstack1,1))
printf("\n1号栈目前为空!\n");
else
printf("\n1号栈不为空!\n");
return 0;
}
友情链接:
https://blog.csdn.net/ssopp24/article/details/71427894?locationNum=8&fps=1