数据结构与算法题目集(中文)7-22 堆栈模拟队列 (25分)

1.题目

设已知有两个堆栈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()

输入格式:

输入首先给出两个正整数N1N2,表示堆栈S1S2的最大容量。随后给出一系列的队列操作: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

2.题目分析

1.输入两个栈的大小,让1栈为小的那一个 

2.输入时

  1. s1没满,s2为空,输入到s1中。

  2. s1满了,s2为空,将s1中的数据倒入s2中,再输入到s1中。

  3. s1满了,s2不为空,输出ERROR:Full。

3.输出时

  1. s2不是空的,直接输出s2.top()。

  2. s2是空的,s1不是空的,将s1中的元素倒入s2中,再输出s2.top()。

  3. s2是空的,s1也是空的,输出ERROR:Empty。

3.代码

#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
int main()
{
	stack<int>a, b;
	int c, d;
	cin >> c >> d;
	if (c > d)swap(c, d);//让1为小栈
	while (1)
	{
		char temp1;
		cin >> temp1;
		if (temp1 == 'T')
			break;

		if (temp1 == 'A')
		{
			int temp2;
			cin >> temp2;
			if (a.size() < c)//1栈没满
			{
				a.push(temp2);
			}
			else
			{
				if (b.empty())//2栈为空
				{
					while (!a.empty())
					{
						int temp = a.top(); a.pop();
						b.push(temp);
					}
					a.push(temp2);
				}
				else
				{
					cout << "ERROR:Full" << endl;
				}
			
			}
		}
		else if (temp1 == 'D')
		{
			if (!b.empty())//2栈不空
			{
				int  temp = b.top(); b.pop();
				cout << temp << endl;
			}
			else//2栈为空
			{
				if (!a.empty())//1栈不空
				{
					while (!a.empty())
					{
						int temp = a.top(); a.pop();
						b.push(temp);
					}
					int  temp = b.top(); b.pop();
					cout << temp << endl;
				}
				else//1栈也为空
				{
					cout << "ERROR:Empty" << endl;
				}
			}
		
		}


	}
	


}

 

posted @ 2020-02-08 17:54  Jason66661010  阅读(183)  评论(0编辑  收藏  举报