3-9 堆栈模拟队列 (20分)
最棒的!!!
大佬的思路
记容量小的栈为s1,容量大的栈为s2
输入时
s1没满,s2为空,输入到s1中。 s1满了,s2为空,将s1中的数据倒入s2中,再输入到s1中。
s1满了,s2不为空,输出ERROR:Full。
输出时s2不是空的,直接输出s2.top()。 s2是空的,s1不是空的,将s1中的元素倒入s2中,再输出s2.top()。
s2是空的,s1也是空的,输出ERROR:Empty。 设已知有两个堆栈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
AC
简单的说一下,这道题自己写了好久,但是别人都说是很快很简单,QAQ。。。
参考别的写的,链接在这里,想看解析自取。
3-9 堆栈模拟队列 (20分) HBU-DS
下面这个是人家的answer。通过了啊
我是笨蛋,我不会
#include <iostream>
using namespace std;
typedef struct SNode *Stack;
struct SNode
{
int *data;
int top;
int MaxSize;
};
Stack CreatStack(int n)
{
Stack s = (Stack)malloc(sizeof(SNode));
s->MaxSize = n;
s->data = (int *)malloc(sizeof(int) * n);
s->top = -1;
return s;
}
int main()
{
int N1, N2;
cin >> N1 >> N2;
if (N1 > N2)
{
int temp = N1;
N1 = N2;
N2 = temp;
}
Stack s1 = CreatStack(N1);
Stack s2 = CreatStack(N2);
char op;
int n;
while (cin >> op)
{
if (op == 'T')
break;
if (op == 'A')
{
cin >> n;
if (s1->top == s1->MaxSize - 1) //a full
{
if (s2->top != -1) //b no empty
cout << "ERROR:Full" << endl;
else
{
while (s1->top != -1)
s2->data[++s2->top] = s1->data[s1->top--];
s1->data[++s1->top] = n;
}
}
else // a 没满
s1->data[++s1->top] = n;
}
else if (op == 'D')
{
if (s2->top == -1) //b empty
{
if (s1->top == -1)
cout << "ERROR:Empty" << endl;
else
{
while (s1->top != -1)
s2->data[++s2->top] = s1->data[s1->top--];
cout << s2->data[s2->top--] << endl;
}
}
else //b 有东西
cout << s2->data[s2->top--] << endl;
}
}
}
记得来改答案:
#include <iostream>
using namespace std;
int main() {
int N1,N2;
cin>>N1>>N2;
if(N1>N2) {
int n=N1;
N1=N2;
N2=n;
}
int ss1=-1,ss2=-1;
int s1[N1],s2[N2];
char ch;
while(cin>>ch&&ch!='T') {
if(ch=='A') {
int n;
cin>>n;
if(ss1==N1-1) {//s1 is full
if(ss2!=-1) {//s2 is not full
//因为无法倒腾
cout<<"ERROR:FULL"<<endl;
}
else {//s2 is full
while(ss1!=-1) {
//把s1里的数据全部转入s2中。这个时候s2最上面的数字就是下一个要弹出的
s2[++ss2]=s1[ss1--];
}
s1[++ss1]=n;//再次把新的数字存入s1的空表
}
}
else {//s1 is not full ,直接存入
s1[++ss1]=n;
}
}
else if(ch=='D') {
if(ss2==-1) {//s2 is full
if(ss1==-1) {//s1 is full
cout<<"ERROR:Empty"<<endl;
}
else {//s1 is not full
while(ss1!=-1) {
//把s1导入s2里,再从s2输出
s2[++ss2]=s1[ss1--];
}
cout<<s2[ss2--]<<endl;//输出需要弹出的数据
}
}
else {//s2 is not full
cout<<s2[ss2--]<<endl;
}
}
}
return 0;
}