LeetCode 225. 用队列实现栈
原题链接
简单
作者:
Bug-Free
,
2021-08-20 19:41:11
,
所有人可见
,
阅读 515
class MyStack {
public:
queue<int> q1;
queue<int> q2;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while(q1.size() > 1 ) {
q2.push(q1.front());
q1.pop();
}
int ans = q1.front();
q1.pop();
while (q2.size()) {
q1.push(q2.front());
q2.pop();
}
return ans;
}
/** Get the top element. */
int top() {
while(q1.size() > 1 ) {
q2.push(q1.front());
q1.pop();
}
int ans = q1.front();
q1.pop();
while (q2.size()) {
q1.push(q2.front());
q2.pop();
}
q1.push(ans);
return ans;
}
/** 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();
*/