用两个栈模拟队列实例(C++)

C++中能方便的建立栈(stack)和队列(queue);

但如何用两个站模拟队列呢;

(不足:只能存正整数,因为定义了正整数栈;)

下面是其中一种思路;

//This code was write by Hupeng
//This code could run in VS 2013
#include <iostream>
#include <stack>
#include <conio.h>
using namespace std;
class queue
{
public:
	void push(int n)
	{
		STD_stack.push(n);
	}
	int pop()
	{
		int n;
		while (!STD_stack.empty())
		{
			STD_temp.push(STD_stack.top());
			STD_stack.pop();
		}
		n = STD_temp.top();
		STD_temp.pop();
		while (!STD_temp.empty())
		{
			STD_stack.push(STD_temp.top());
			STD_temp.pop();
		}
		return n;
	}
	int front()
	{
		int n;
		while (!STD_stack.empty())
		{
			STD_temp.push(STD_stack.top());
			STD_stack.pop();
		}
		n = STD_temp.top();
		while (!STD_temp.empty())
		{
			STD_stack.push(STD_temp.top());
			STD_temp.pop();
		}
		return n;
	}
	int empty()
	{
		if (STD_stack.empty())
			return 1;
		return 0;
	}
protected:
private:
	stack<int>STD_stack;
	stack<int>STD_temp;
};
int main()
{
	char c;
	int n;
	int flag = 0;
	queue example;
	cout << "这是一个整型队列(尽量储存正整数):" << endl;
	while (true)
	{
		cout << "请选择所要进行的操作:" << endl;
		cout << "1. push" << endl << "2. pop" << endl << "3. front" << endl << "4. empty" << endl << "0. exit" << endl;
		c = _getch();
		switch (c)
		{
		case '0':  flag = 1; break;
		case '1':
		{
			cout << "请输入一个正数:" << endl;
			cin >> n;
			example.push(n);
		}break;
		case '2':
		{
			if (example.empty())
			{
				cout << "队列为空!" << endl;
			}
			else
			{
				cout << "弹出:" << example.pop() << endl;
			}
		} break;
		case '3':
		{
			if (example.empty())
			{
				cout << "队列为空!" << endl;
			}
			else
			{
				cout << "队首元素:" << example.front() << endl;
			}
		}break;
		case '4':
		{
			if (example.empty())
			{
				cout << "队列为空!" << endl;
			}
			else
			{
				cout << "队列不为空!" << endl;
			}
		}
		default:
			break;
		}
		if (flag)
		{
			break;
		}
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值