两个栈实现一个队列

栈的特性:先进后出
队列的特性:先进先出

这个原理就跟用两个杯子倒出沉淀物一样,先把 1 杯子上面的水倒入 2 杯子中,然后把 1 杯子的沉淀物取出,再把 2 杯子中的倒入到 1 中…依次循环

下面我们用代码实现:

#include <iostream>
#include <stack>
using namespace std;
class stackQueue {
	stack<int>m_s1;
	stack<int>m_s2;

public:
	stackQueue() {

	}
	void push(int i) {
		m_s1.push(i);
	}
	void pop() {
		while (m_s1.size() > 1) {
			m_s2.push(m_s1.top());
			m_s1.pop();
		}
		m_s1.pop();
		while (!m_s2.empty()) {
			m_s1.push(m_s2.top());
			m_s2.pop();
		}


	}

	int front() {
		while (m_s1.size() > 1) {
			m_s2.push(m_s1.top());
			m_s1.pop();
		}
		int tmp=m_s1.top();

		while (!m_s2.empty()) {
			m_s1.push(m_s2.top());
			m_s2.pop();
		}
		return tmp;
	}
	int back() {
		return m_s1.top();
	}
};

int main() {
	stackQueue sq;
	sq.push(2);
	sq.push(3);
	sq.push(4);

	cout << sq.front() << endl;
	sq.pop();
	cout << sq.front() << endl;
	sq.pop();
	cout << sq.front() << endl;
	sq.pop();

	system("pause");
	return 0;
}

输出结果如图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值