本文主要是介绍Leetcode|队1出栈+队2中转|225. 用两个队列实现栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《225. 用两个队列实现栈》
《剑指 Offer 09. 用两个栈实现队列》
1 队1出栈+队2中转
- 两个队列q1和q2,新入栈的元素先放入q2,然后将q1中元素逐个入队q2,再交换2队列即可
class MyStack {
public:queue<int> q1, q2;/** Initialize your data structure here. */MyStack() {}/** Push element x onto stack. */void push(int x) {q2.push(x);while (!q1.empty()) {q2.push(q1.front());q1.pop();}swap(q1, q2);}/** Removes the element on top of the stack and returns that element. */int pop() {int res;if (q1.empty()) return -1;res = q1.front();q1.pop();return res;}/** Get the top element. */int top() {if (q1.empty()) return -1;return q1.front();}/** Returns whether the stack is empty. */bool empty() {return q1.empty();}
};/*** Your MyStack object will be instantiated and called as such:* MyStack* obj = new MyStack();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->top();* bool param_4 = obj->empty();*/
这篇关于Leetcode|队1出栈+队2中转|225. 用两个队列实现栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!