C++——用队列实现栈

用队列实现栈

一.问题描述:

自己设计一个栈,用队列来实现其基本接口。

解题思路:

1.入栈:向非空队列内插入元素

2.出栈:先将非空队列中的前n-1个元素插入到空队列中并出队,再将原非空队列中的元素出队即可。

3.获取栈顶元素:即获取非空队列的队尾元素。

4.判断栈是否为空:两个队列均为空时即该栈为空。

二.代码实现

#include <iostream>
#include <queue>
using namespace std;

class MyStack {
public:
	/** Initialize your data structure here. */
	MyStack() {

	}

	/** Push element x onto stack. */
	void push(int x) {
		//向非空队列中插入元素
		if (q1.empty())
			q2.push(x);
		else
			q1.push(x);
	}

	/** Removes the element on top of the stack and returns that element. */
	int pop() {
		//将非空队列中的前n-1个元素移动到空队列中去
		if (q1.empty()) {
			while (q2.size()>1) {
				q1.push(q2.front());
				q2.pop();
			}
			int ret = q2.front();
			q2.pop();
			return ret;
		}
		else {
			while (q1.size()>1) {
				q2.push(q1.front());
				q1.pop();
			}
			int ret = q1.front();
			q1.pop();
			return q1.front();
		}
	}

	/** Get the top element. */
	int top() {
		if (q1.empty()) {
			return q2.back();
		}
		else
			return q1.back();
	}

	/** Returns whether the stack is empty. */
	bool empty() {
		return q1.empty()
			&& q2.empty();
	}
	queue<int> q1;
	queue<int> q2;
};

int main() {
	MyStack s;
	s.push(1);
	s.push(2);
	cout << s.top() << endl;
	cout << s.pop() << endl;
	system("pause");
	return 0;
}

三.总结

把握两个队列交替插入元素,进行元素的交替;过程中必然有一个队列是空队列

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值