题目要求:
我的代码实现:(两个顺序栈)
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define MaxSize 50
//顺序栈基本数据类型定义:
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S)
{
for(int i=0;i<MaxSize;i++)S.data[i]=0;
S.top=0;
}
bool Push(SqStack &S,ElemType x)
{
if(S.top==MaxSize)return false;
S.data[S.top++]=x;
return true;
}
bool Pop(SqStack &S,ElemType &x)
{
if(S.top==0)return false;
x=S.data[--S.top];
return true;
}
bool StackEmpty(SqStack &S)
{
if(S.top==0)return true;
else return false;
}
bool StackOverflow(SqStack &S)
{
if(S.top==MaxSize)return true;
else return false;
}
SqStack S1,S2; //定义两个用来模拟队列的栈
//用两个栈所模拟的队列入队:
bool Enqueue(ElemType x)
{
if(StackOverflow(S1))return false;
Push(S1,x);
return true;
}
//用两个栈所模拟的队列判空:
bool QueueEmpty()
{
if(StackEmpty(S1)&&StackEmpty(S2))return true;
else return false;
}
//用两个栈所模拟的队列出队:
bool Dequeue(ElemType &x)
{
ElemType a;
if(StackEmpty(S2)&&StackEmpty(S1))return false;
while(!StackEmpty(S1))
{
Pop(S1,a);
Push(S2,a);
}
Pop(S2,x);
return true;
}
//主函数:
int main()
{
InitStack(S1);
InitStack(S2);
ElemType x;
printf("\n队列元素开始入队:\n");
scanf("%d",&x);
while(x!=9999)
{
Enqueue(x);
scanf("%d",&x);
}
printf("\n队列元素开始出队:\n");
while(!QueueEmpty())
{
Dequeue(x);
printf("%d ",x);
}
printf("\n");
}
本来还想用链栈的,突然意识到如果我用了链栈,就不需要再判满了,就用顺序栈吧。
实现一下王道书的标准答案:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define MaxSize 50
//顺序栈基本数据类型定义:
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S)
{
for(int i=0;i<MaxSize;i++)S.data[i]=0;
S.top=0;
}
bool Push(SqStack &S,ElemType x)
{
if(S.top==MaxSize)return false;
S.data[S.top++]=x;
return true;
}
bool Pop(SqStack &S,ElemType &x)
{
if(S.top==0)return false;
x=S.data[--S.top];
return true;
}
bool StackEmpty(SqStack &S)
{
if(S.top==0)return true;
else return false;
}
bool StackOverflow(SqStack &S)
{
if(S.top==MaxSize)return true;
else return false;
}
SqStack S1,S2; //定义两个用来模拟队列的栈
//用两个栈所模拟的队列入队:
bool Enqueue(SqStack &S1,SqStack &S2,ElemType e)
{
if(!StackOverflow(S1))
{
Push(S1,e);
return true;
}
if(StackOverflow(S1)&&!StackEmpty(S2))
{
printf("\n队列满\n");
return false;
}
if(StackOverflow(S1)&&StackEmpty(S2))
{
ElemType x;
while(!StackEmpty(S1))
{
Pop(S1,x);
Push(S2,x);
}
}
Push(S1,e);
return true;
}
//用两个栈所模拟的队列判空:
bool QueueEmpty(SqStack S1,SqStack S2)
{
if(StackEmpty(S1)&&StackEmpty(S2))return true;
else return false;
}
//用两个栈所模拟的队列出队:
void Dequeue(SqStack &S1,SqStack &S2,ElemType &x)
{
if(!StackEmpty(S2))
{
Pop(S2,x);
}
else if(StackEmpty(S1))
{
printf("\n队列为空\n");
}
else
{
while(!StackEmpty(S1))
{
Pop(S1,x);
Push(S2,x);
}
Pop(S2,x);
}
}
//主函数:
int main()
{
InitStack(S1);
InitStack(S2);
ElemType x;
printf("\n队列元素开始入队:\n");
scanf("%d",&x);
while(x!=9999)
{
Enqueue(S1,S2,x);
scanf("%d",&x);
}
printf("\n队列元素开始出队:\n");
while(!QueueEmpty(S1,S2))
{
Dequeue(S1,S2,x);
printf("%d ",x);
}
printf("\n");
}
王道书给的判空操作跟我之前的想法倒是一样的。但他们的这种算法使得模拟队列的容量增加了。