写在最前面,目前Java已经推荐使用Deque来实现栈和队列了,原因:
https://www.cnblogs.com/jiading/articles/12452830.html
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
judge();
return stackOut.pop();
}
public int peek() {
// 返回队头元素
judge();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void judge() {
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()) {
Integer x = stackIn.pop();
stackOut.push(x);
}
}
}
class MyStack {
Deque<Integer> queueIn;
Deque<Integer> queueOut;
public MyStack() {
queueIn = new ArrayDeque<>();
queueOut = new ArrayDeque<>();
}
public void push(int x) {
queueIn.addLast(x);
}
public int pop() {
transToOut();
Integer x = queueIn.pollFirst();
transToIn();
return x;
}
public int top() {
transToOut();
Integer x = queueIn.pollFirst();
queueOut.addLast(x);
transToIn();
return x;
}
public boolean empty() {
return queueIn.isEmpty() && queueOut.isEmpty();
}
private void transToOut() {
while (queueIn.size() > 1) {
Integer x = queueIn.pollFirst();
queueOut.addLast(x);
}
}
private void transToIn() {
while (queueOut.size() > 0) {
Integer x = queueOut.pollFirst();
queueIn.addLast(x);
}
}
}