免费综合网站注册申请,wordpress 文章描述,软装设计公司介绍,中国电子商务官网7-4 堆栈模拟队列 (25 分)
设已知有两个堆栈S1和S2#xff0c;请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列#xff0c;实际上就是通过调用堆栈的下列操作函数:
int IsFull(Stack S)#xff1a;判断堆栈S是否已满#xff0c;返回1或0#xff1b; int IsEmpty (…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
这道题我一开始用的stl后来遇到重题了就用数组模拟了一遍发现用stl真的是很简单。下面分别附上stl和非stl的方法。
//stl实现
#include bits/stdc.h
using namespace std;
int main()
{stackints1,s2;int m,n,t;cinmn;if (nm){tm;mn;nt;} //s2 smallerchar c;int num;getchar();while (1){scanf(%c,c); //A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D Tif (cT){break;}if (s2.size()ns1.empty()){while(!s2.empty()){s1.push(s2.top());s2.pop();}}if (cAs2.size()!n){scanf(%d ,num);s2.push(num);}else if (cAs2.size()n){scanf(%d,num);printf(ERROR:Full\n);}if (cDs1.empty()){printf(ERROR:Empty\n);}else if (cD!s1.empty()){printf(%d\n,s1.top());s1.pop();}}return 0;
}//数组构建栈模拟
#include bits/stdc.h
using namespace std;
int main()
{int n1,n2,top1-1,top2-1,t;cinn1n2; //n2是比较小的if (n2n1){tn1;n1n2;n2t;}getchar();int s1[100],s2[100]; //3 2char c; //A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D Tint x;scanf(%c,c);while (c!T){if (cA){if(top2n2-1) //如果短的2没满一直填充到2.{scanf(%d,x);s2[top2]x;getchar();}else if (top2n2-1top1!-1) //如果2满了但是1不为空此时无法进行数据移动输出FULL. {scanf(%d,x);getchar();printf(ERROR:Full\n);}else if (top2n2-1top1-1) //如果2满了但是1是空的数据移动全部移过去. {while (top2!-1){s1[top1]s2[top2--];}scanf(%d,x);s2[top2]x;getchar();}}if (cD){getchar();if (top1!-1) //如果1不是空的先输出1因为他的数输入的更早. {printf(%d\n,s1[top1--]);}else if (top2!-1top1-1) //如果2不是空的但是1是空的转换数据再输出. {while (top2!-1){s1[top1]s2[top2--];}printf(%d\n,s1[top1--]);}else if (top1-1top2-1) //都是空的输出错误提示. {printf(ERROR:Empty\n);}}scanf(%c,c);}return 0;
}