225. Implement Stack using Queues
2026/1/12大约 2 分钟约 475 字
225. Implement Stack using Queues
难度: Easy
题目描述
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()Returnstrueif the stack is empty,falseotherwise.
Notes:
- You must use only standard operations of a queue, which means that only
push to back,peek/pop from front,sizeandis emptyoperations are valid. - Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
Example 1:
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
Constraints:
1 <= x <= 9- At most
100calls will be made topush,pop,top, andempty. - All the calls to
popandtopare valid.
Follow-up: Can you implement the stack using only one queue?
解题思路
代码实现
解决方案
java
class MyStack {
private Queue<Integer> q1;
private Queue<Integer> q2;
private int top;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q1.offer(x);
top = x;
}
public int pop() {
if (q1.isEmpty()) {
top = 0;
return 0;
}
while (q1.size() > 1) {
if (q1.size() == 2) {
top = q1.peek();
}
q2.offer(q1.poll());
}
int res = q1.poll();
while (q2.size() > 0) {
q1.offer(q2.poll());
}
if (q1.size() == 0) {
top = 0;
}
return res;
}
public int top() {
return top;
}
public boolean empty() {
return q1.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();
*/