アイデア: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;
};