Problem: 232. 用栈实现队列
思路
当使用一个栈的时候 如果要删除栈底的元素 需要将上面的元素都出栈 效率非常的低下 如果使用2个栈 那么A栈实现删除栈顶 B栈负责实现倒序 从而删除栈底
解题方法
image.png
Code
class MyQueue {
private Stack<Integer> A;
private Stack<Integer> B;
public MyQueue() {
A = new Stack<>();
B = new Stack<>();
}
/**
* 将元素 x 推到队列的末尾
* @param x
*/
public void push(int x) {
A.push(x);
}
/**
* 从队列的开头移除并返回元素
* @return
*/
public int pop() {
int peek = peek();
B.pop();
return peek;
}
/**
* 返回队列开头的元素
* @return
*/
public int peek() {
if (!B.isEmpty()) {
return B.peek();
} else if (A.isEmpty()) {
return -1;
}else {
while (!A.isEmpty()) {
B.push(A.pop());
}
return B.peek();
}
}
/**
* 如果队列为空,返回 true ;否则,返回 false
* @return
*/
public boolean empty() {
return A.isEmpty() && B.isEmpty();
}
}