LeetCode 225-ImplementStackUsingQueues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push
, top
, pop
, and empty
).
Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns it.int top()
Returns the element on the top of the stack.boolean empty()
Returns true if the stack is empty, false otherwise.Notes:
push to back
, peek/pop from front
, size
and is empty
operations are valid.입력:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
출력:
[null, null, null, 2, 2, false]
class MyStack {
Queue<Integer> q1;
Queue<Integer> q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q2.offer(x);
while(!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.isEmpty();
}
}
Queue의 기본 메서드들을 잘 봐야겠다..!