문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
두 개의 스택만 사용해서 선입선출(FIFO)를 구현해라. 구현된 큐는 기본적인 큐의 모든 기능(push, peek, pop, empty)을 지원해야한다.
구현할 MyQueue 클래스
Input
["MyQueue", "push", "push", "peek", "pop", "empty"][[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); queue is: [1]
myQueue.push(2); queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false;
class MyQueue {
private Stack<Integer> input;
private Stack<Integer> output;
public MyQueue() {
input = new Stack<>();
output = new Stack<>();
}
public void push(int x) {
input.push(x);
}
public int pop() {
peek();
return output.pop();
}
public int peek() {
if(output.isEmpty()){
while(!input.isEmpty()){
output.push(input.pop());
}
}
return output.peek();
}
public boolean empty() {
return input.isEmpty() && output.isEmpty();
}
}
/**
* 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();
*/