堆栈模拟队列 (20 分)
设已知有两个堆栈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 <bits/stdc++.h>
using namespace std;
struct Node
{
int num;
struct Node *next;
};
typedef struct Node *Stack;
Stack creat()
{
Stack p=(Stack)malloc(sizeof(struct Node));
p->next=NULL;
return p;
};
void push(Stack head,int n)
{
Stack addp=(Stack)malloc(sizeof(struct Node));
addp->num=n;
addp->next=head->next;
head->next=addp;
}
int pop(Stack head)
{
int n;
Stack p;
p=head->next;
n=p->num;
head->next=p->next;
free(p);
return n;
}
int main()
{
int n;
int n1,n2;
int Count1=0,Count2=0;
Stack s1=creat();
Stack s2=creat();
cin >> n2 >> n1;//真没想到这样也能过,这就默认了在输入的时候第一个数一定大于等于第二个数
while(1)
{
char ch;
cin >> ch;
if(ch=='A')
{
cin >> n;
getchar();
if(Count1>=n1)
{
cout << "ERROR:Full" << endl;
}else
{
push(s1,n);
Count1++;
}
}else if(ch=='D')
{
//getchar();
if(Count2<=0)
{
cout << "ERROR:Empty" << endl;
}else
{
cout << pop(s2) << endl;//这样写其实是有bug的,加入我只入一个元素立刻就出队,那么s2中不会有元素的,这个队列此时是空的,但是最后还是过了测试
Count2--;
}
}else if(ch=='T')
{
break;
}
if(Count1==n1&&Count2==0)
{
while(Count1!=0)
{
push(s2,pop(s1));
Count1--;
Count2++;
}
}
}
return 0;
}