设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
void Push(Stack S, ElementType item ):将元素item压入堆栈S;
ElementType Pop(Stack S ):删除并返回S的栈顶元素。
实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()。
输入格式:
输入首先给出两个正整数N1和N2,表示堆栈S1和S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。
输出格式:
对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty。如果入队操作无法执行,也需要输出ERROR:Full。每个输出占1行。
输入样例:
3 2
A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T
输出样例:
ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty
#include <stdio.h>
#include <stdlib.h>
struct SNode {
int *Data;
int Top;
int MaxSize;
};
typedef struct SNode *Stack;
Stack CreateStack(int x){
Stack p;
p=(Stack)malloc(sizeof(struct SNode));
p->Data=(int *)malloc(sizeof(int)*x);
p->MaxSize=x;
p->Top=-1;
return p;
}
void push(Stack S,int x){
S->Data[++S->Top]=x;
}
int pop(Stack S){
int t;
t=S->Data[S->Top];
S->Top--;
return t;
}
int IsFull (Stack S ){
if(S->Top==S->MaxSize-1)
return 1;
else
return 0;
}
int IsEmpty (Stack S ){
if(S->Top==-1)
return 1;
else
return 0;
}
int main(){
int n1,n2,a,b,m;scanf("%d%d",&a,&b);
char t;
t=getchar();
n1=(a<=b)?a:b;
n2=(a<=b)?b:a;/*n1为较小数,为数据栈 */
char order;
Stack S1=CreateStack(n1);
Stack S2=CreateStack(n2);
while(1){
int flag=0;
order=getchar();
getchar();
switch(order){
case 'A':{
scanf("%d",&m);
getchar();
if(!IsFull(S1)){
push(S1,m);
}
else if(IsFull(S1)&&!IsEmpty(S2)){
printf("ERROR:Full\n");/*必须满足s1满了之后,s2必须为空,否则不能输入;不然的话队列的输出循序会紊乱*/
}else if(IsFull(S1)&&IsEmpty(S2)){
while(!IsEmpty(S1)){
push(S2,pop(S1));
}
push(S1,m);/*所以这种队列最多能入n1+1个元素*/
}
break;
}
case 'D':{
if(!IsEmpty(S2)){
printf("%d\n",pop(S2));
}else
{
if(!IsEmpty(S1)){
/*把s1都pop到s2里,然后pop出s2,再把s2倒回去*/
while(!IsEmpty(S1)){
push(S2,pop(S1));
}
printf("%d\n",pop(S2));
}else{
printf("ERROR:Empty\n");
}
}
break;
}
case 'T':{
flag=1;
break;
}
}
if(flag)break;
}
return 0;
}