7-4 堆栈模拟队列(25 分)
设已知有两个堆栈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
用c写的代码,自己运行和答案一样,但是pta不通过,显示答案错误,pta提交后的情况在最底下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct work *node;
struct work
{
int *n;
int top;
};
typedef node stack;
stack creast(int n);
void push(stack p,char x);
int pop(stack p);
int empty(stack p);
void push_pop(stack p,stack s);
int main()
{
int n,m;
scanf("%d %d",&n,&m);
stack p=creast(n),s=creast(m);
if(n>m) n^=m^=n^=m;
char a;
int flag=1,x;
while(flag)
{
scanf("%c",&a);
switch(a)
{
case 'A':
scanf("%d",&x);
if(p->top==n-1&&!empty(s))
{
printf("ERROR:Full\n");
}
else
{
if(p->top==n-1)
{
push_pop(p,s);
}
push(p,x);
}
break;
case 'D':
scanf("%d",&x);
if(empty(p)&&empty(s))
{
printf("ERROR:Empty\n");
}
else
{
if(empty(s))
{
push_pop(p,s);
}
printf("%d\n",pop(s));
}
break;
case 'T':
flag=0;
break;
}
}
return 0;
}
stack creast(int n)
{
stack p=(stack)malloc(sizeof(struct work));
p->n=(int *)malloc(sizeof(int)*n);
p->top=-1;
return p;
}
void push(stack p,char x)
{
p->n[++(p->top)]=x;
}
int pop(stack p)
{
if(p->top!=-1)
return p->n[p->top--];
}
int empty(stack p)
{
if(p->top==-1)
{
return 1;
}
else
{
return 0;
}
}
void push_pop(stack p,stack s)
{
while(p->top!=-1)
{
push(s,p->n[p->top--]);
}
}