import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Queue {
Deque<Integer> s1 = new ArrayDeque<>();
Deque<Integer> s2 = new ArrayDeque<>();
public void push(Integer i){
while(!s1.isEmpty()){
s2.push(s1.poll());
}
s2.push(i);
while(!s2.isEmpty()){
s1.push(s2.poll());
}
}
public Integer poll(){
return s1.poll();
}
public Integer top(){
return s1.peek();
}
public static void main(String[] args) {
Queue q1 = new Queue();
q1.push(1);
q1.push(2);
q1.push(3);
System.out.println(q1.top());
System.out.println(q1.poll());
System.out.println(q1.poll());
System.out.println(q1.poll());
}
}
核心思想,把stack2当成添加时的工具栈
添加的时候,先把stack1的元素放入stack2,添加完之后,把所有元素放回stack1。
poll的时候,直接从stack1出
每次添加都是在stack2最外层添加,到了stack1,自然到了最内层