Topic:Implement a MyQueue class which implements a queue using two stacks.
//方法:两个stack,第一个吃(push),第二个吃(pop)第一个吐出来的,然后再吐。
优化:Dequeue第二个,when empty, transfer all elements from第一个。
import java.util.Stack;
public class MyQueue<T> {//<T>这里的不能掉了
Stack<T> stack1, stack2;
public MyQueue(){
stack1=new Stack<T>();
stack2=new Stack<T>();
}
public int size(){//注意这里
return stack1.size()+stack2.size();
}
public void add(T value){
stack1.push(value);
}
public void shiftStacks(){
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop()); //有意思的是这一句
}
}
}
public T peek(){//队列的peek应该是oldest,即stack2的peek
shiftStacks();
return stack2.peek();
}
public static void main(String[] args) {
MyQueue<Integer> queue=new MyQueue<Integer>();
for(int i=0;i<5;i++){
queue.add(i);
}
queue.shiftStacks();
System.out.println(queue.peek());
}
}
//结果
0