LeetCode 232. 用栈实现队列
原题链接
简单
作者:
caichuntao
,
2023-06-29 09:09:31
,
所有人可见
,
阅读 69
方法1:双栈
时间复杂度:$O(1)$
空间复杂度:$O(n)$
解题思路
https://leetcode.cn/problems/implement-queue-using-stacks/solution/yong-zhan-shi-xian-dui-lie-by-leetcode-s-xnb6/
Java 代码
class MyQueue {
Stack<Integer> stk1;
Stack<Integer> stk2;
public MyQueue() {
stk1 = new Stack<>();
stk2 = new Stack<>();
}
public void push(int x) {
stk1.push(x);
}
public int pop() {
if (stk2.isEmpty()) {
in2out();
}
return stk2.pop();
}
public int peek() {
if (stk2.isEmpty()) {
in2out();
}
return stk2.peek();
}
public boolean empty() {
return stk1.isEmpty() && stk2.isEmpty();
}
public void in2out() {
while (!stk1.isEmpty()) {
stk2.push(stk1.pop());
}
}
}
/**
* 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();
*/