【题目】
来源:leetcode
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
【代码】两个栈模拟一个队列
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :7 MB, 在所有 C++ 提交中击败了100.00%的用户
class MyQueue {
private:
stack<int> s1,s2;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int x=peek();
s2.pop();
return x;
}
/** Get the front element. */
int peek() {
if(!s2.empty())
return s2.top();
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(s1.empty()&&s2.empty())
return true;
return false;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/