思路:用2个栈,元素经过2个栈之后,顺序就和队列顺序一样了
class MyQueue {
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() {
if(s2.size()==0){
while(s1.size()){
s2.push(s1.top());
s1.pop();
}
}
int res = s2.top();
s2.pop();
return res;
}
/** Get the front element. */
int peek() {
if(s2.size()==0){
while(s1.size()){
s2.push(s1.top());
s1.pop();
}
}
int res = s2.top();
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.size()==0 && s2.size()==0;
}
private:
stack<int> s1,s2;
};