難易度
Easy
アプローチ
Stack
class MyQueue {
public Stack<Integer> mainStack;
public Stack<Integer> subStack;
public MyQueue() {
mainStack = new Stack<>();
subStack = new Stack<>();
}
public void push(int x) {
mainStack.add(x);
}
public int pop() {
while(!mainStack.empty()){
subStack.add(mainStack.pop());
}
int result = subStack.pop();
mainStack = new Stack<>();
while(!subStack.empty()){
mainStack.add(subStack.pop());
}
subStack = new Stack<>();
return result;
}
public int peek() {
while(!mainStack.empty()){
subStack.add(mainStack.pop());
}
int result = subStack.peek();
mainStack = new Stack<>();
while(!subStack.empty()){
mainStack.add(subStack.pop());
}
subStack = new Stack<>();
return result;
}
public boolean empty() {
return mainStack.empty();
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/