문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
두 개의 큐만 사용해서 후입선출(LIFO)를 구현해라. 구현된 스택은 일반 스택의 모든 기능(push, top, pop, empty)을 지원해아 한다.
Input
["MyStack", "push", "push", "top", "pop", "empty"][[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return false;
class MyStack {
private Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
for(int i = 0; i < queue.size() - 1; i++){
queue.add(queue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/