https://leetcode-cn.com/problems/implement-queue-using-stacks/
终于进入队列系列题目了,JAVA用Deque双端队列模拟栈,然后实现队列,先用O(n)算法
class MyQueue {
Deque<Integer> in;
Deque<Integer> out;
/** Initialize your data structure here. */
public MyQueue() {
in = new LinkedList<Integer>();
out = new LinkedList<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!out.isEmpty()) in.addLast(out.pollLast());
in.addLast(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while(!in.isEmpty()) out.addLast(in.pollLast());
return out.pollLast();
}
/** Get the front element. */
public int peek() {
while(!in.isEmpty()) out.addLast(in.pollLast());
return out.peekLast();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
思路:
1.push只对in栈进行操作,只要push就往in里面放元素
2.pop操作,由于队列是先进先出,而栈是先进后出,而in是栈,要pop in的第一个元素,需要把in的元素全部倒腾到out里去,再把out的最后一个元素pop掉,就相当于队列的pop,peek也是同理。
3.由于不确定调用empty函数前,in和out是哪个全满,所以两个一起判断。
再上一种均摊O(1)的算法
class MyQueue {
Deque<Integer> in;
Deque<Integer> out;
/** Initialize your data structure here. */
public MyQueue() {
in = new LinkedList<Integer>();
out = new LinkedList<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.addLast(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(out.isEmpty()){
while(!in.isEmpty()) out.addLast(in.pollLast());
}
return out.pollLast();
}
/** Get the front element. */
public int peek() {
if(out.isEmpty()) {
while(!in.isEmpty()) out.addLast(in.pollLast());
}
return out.peekLast();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
这个就是不是每次push都需要in全满,out全空状态,倒腾的时机是当out为空时,把in的元素全部倒腾过来,由于out已经是队列顺序的先进先出,所以无论怎么push,只要push到in里面去,pop和peek只针对out的元素,只有out为空时,才需要把in的元素全部倒腾到out里去。