Problem: 225. 用队列实现栈
思路
Code
class MyStack {
private Queue<Integer> A;
private Queue<Integer> B;
public MyStack() {
A = new LinkedList<>();
B = new LinkedList<>();
}
/**
* 将元素 x 压入栈顶。
* @param x
*/
public void push(int x) {
A.offer(x);
while (!B.isEmpty()) {
A.offer(B.poll());
}
while (!A.isEmpty()) {
B.offer(A.poll());
}
}
/**
* 移除并返回栈顶元素。
* @return
*/
public int pop() {
Integer peek = B.peek();
B.poll();
return peek;
}
/**
* 返回栈顶元素。
* @return
*/
public int top() {
return B.peek();
}
/**
* 如果栈是空的,返回 true ;否则,返回 false 。
* @return
*/
public boolean empty() {
return B.isEmpty();
}
}