Problem: 232. 用栈实现队列
文章目录
- 思路
- 复杂度
- 💖 朴素版
- 💖 优化版
思路
👨🏫 路飞题解
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
💖 朴素版
class MyQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
s2.push(x);
while(!s2.isEmpty())
{
s1.push(s2.pop());
}
}
public int pop() {
return s1.pop();
}
public int peek() {
return s1.peek();
}
public boolean empty() {
return s1.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();
*/
💖 优化版
class MyQueue {
private Stack<Integer> A;
private Stack<Integer> B;
public MyQueue() {
A = new Stack<>();
B = new Stack<>();
}
public void push(int x) {
A.push(x);
}
public int pop() {
int peek = peek();
B.pop();
return peek;
}
public int peek() {
if (!B.isEmpty()) return B.peek();
if (A.isEmpty()) return -1;
while (!A.isEmpty()){
B.push(A.pop());
}
return B.peek();
}
public boolean empty() {
return A.isEmpty() && B.isEmpty();
}
}