用两个栈实现一个队列

栈的定义--Stack

栈只允许在末端进行插入和删除的线性表。栈具有后进先出的特性(LIFO,Last In First Out)。
 
队列的定义--Queue
队列值允许在表的队尾进行插入,在表对头进行删除。队列具有先进先出的特性(FIFO,first In First Out)。
思路:1、栈_s1为空时,给_s1依次插入a、b、c。
           2、把_s1中的元素逐个弹出压入_s2,弹出_s2栈顶元素
           3、再插入元素时重复1-2步。
 
 
#include<iostream>
#include<stack>
using namespace std;

template<class T>
class Queue
{
public:
	void Push(const T& x)
	{
		while (!_s2.empty())
		{
			_s1.push(_s2.top());
			_s2.pop();
		}
		_s1.push(x);
	}
	void Pop()
	{
		while (!_s1.empty())
		{
			T& top = _s1.top();
			_s1.pop();
			_s2.push(top);
		}
		_s2.pop();
	}
	bool Empty()
	{
		return _s2.empty() && _s1.empty();
	}
	const T& Gettop()
	{
		while (!_s1.empty())
		{
			_s2.push(_s1.top());
			_s1.pop();
		}
		return _s2.top();
	}
private:
	stack<T> _s1;
	stack<T> _s2;
};
int main()
{
	Queue<int> q;
	q.Push(1);
	q.Push(2);
	q.Push(3);
	q.Push(4);
	q.Push(5);
	
	q.Pop();
	q.Pop();

	q.Push(6);
	q.Push(7);
	while (!q.Empty())
	{
		cout << q.Gettop() << " ";
		q.Pop();
	}
	cout << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值