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;
}

三.总结

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

发布了58 篇原创文章 · 获赞 43 · 访问量 4408

猜你喜欢

转载自blog.csdn.net/Wz_still_shuai/article/details/91663395