232. Implement Queue using Stacks
用stack 实现队列的基本功能,比如入队(队尾巴), 出队(在队头出现队列)
- s1作输入栈,逐个元素压栈,以此模拟队列元素的入队。直接入队列即可
-
- 如果s2不为空的话,直接pop(),直接弹出来的情况
- 如果为空的话,需要将s1中的值进行转过即可
==helper的功能就是将元素从s1移动到s2 ==
可以将helper代码放在peek中
将peek()和push()操作进行之前都需要进行
代码
push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
class MyQueue {
Stack<Integer> input = new Stack();
Stack<Integer> output = new Stack();
public void push(int x) {
input.push(x);
}
public void pop() {
peek();
output.pop();
}
public int peek() {
if (output.empty())
while (!input.empty())
output.push(input.pop());
return output.peek();
}
public boolean empty() {
return input.empty() && output.empty();
}
}
将helper代码抽象抽象出来
class MyQueue {
/** Initialize your data structure here. */
private Stack<Integer> in;
private Stack<Integer> out;
public MyQueue() {
in =new Stack<>();
out = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
helper();
return out.pop();
}
/** Get the front element. */
private void helper(){
if(out.isEmpty()){
while(!in.isEmpty()){
out.push(in.pop());
}
}
}
public int peek() {
//如果in中有元素的情况
//处理前面的元素, 如果
helper();
return out.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}