🌗 232. 用栈实现队列
2022年6月20日
- algorithm
🌗 232. 用栈实现队列
难度: 🌗
问题描述
解法
class MyQueue {
LinkedList<Integer> stack1;
LinkedList<Integer> stack2;
public MyQueue() {
stack1 = new LinkedList<>();
stack2 = new LinkedList<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
// 将 stack1 中的元素依次压入 stack2
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
// stack2 栈顶元素为 队列头元素
int res = stack2.pop();
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return res;
}
public int peek() {
// 将 stack1 中的元素依次压入 stack2
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
// stack2 栈顶元素为 队列头元素
int res = stack2.peek();
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return res;
}
public boolean empty() {
return stack1.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();
*/