方法一:输出栈+输入栈
采用两个栈,一个命名为输入栈,一个命名为输出栈。 各个函数实现思路如下:
- 插入元素时:插入到输入栈中。
- 移除元素时:判断输出栈是否为空。
- 如果为空->将输入栈的元素移到输出栈中->移除输出栈的元素。
- 不为空->移除输出栈的元素。
- 返回首部元素:类似上面的
- 输入站和输出站都为空才true
class MyQueue {
Stack<Integer> input;
Stack<Integer> output;
public MyQueue() {
input = new Stack<>();
output = new Stack<>();
}
public void push(int x) {
input.push(x);
}
public int pop() {
if (output.isEmpty()) {//一定要确认output栈空了,如果不空的话,先pop里面的。
while (!input.isEmpty()) {
output.push(input.pop());
}
}
return output.pop();
}
public int peek() {
if (output.isEmpty()) {
while (!input.isEmpty()) {
output.push(input.pop());
}
}
return output.peek();
}
public boolean empty() {
return input.isEmpty() && output.isEmpty();
}
}
方法二:
每次pop或peek完都要倒一下
class MyQueue {
Stack<Integer> stack;
public MyQueue() {
stack = new Stack<>();
}
public void push(int x) {
stack.push(x);
}
public int pop() {
Stack<Integer> helper = new Stack<>();
while (!stack.isEmpty()) {
helper.push(stack.pop());
}
int res = helper.pop();
while (!helper.isEmpty()) {
stack.push(helper.pop());
}
return res;
}
public int peek() {
Stack<Integer> helper = new Stack<>();
while (!stack.isEmpty()) {
helper.push(stack.pop());
}
int res = helper.peek();
while (!helper.isEmpty()) {
stack.push(helper.pop());
}
return res;
}
public boolean empty() {
return stack.isEmpty();
}
}