import java.util.Stack;
/**
* 实现一个MyQueue类,该类用两个栈来实现一个队列
* Created by rgl on 2018/10/24.
*/
public class MyQueue<T> {
Stack <T> stackNewest, stackOldest;
public MyQueue() {
stackNewest = new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size() + stackOldest.size();
}
//add new element, push value to stackNewest
public void add(T value) {
stackNewest.push(value);
}
//move all the elements in stackNewest to stackOldest, so that we can pop elements as a queue
private void shiftStacks() {
if ( stackOldest.isEmpty() ) {
while ( !stackNewest.isEmpty() ) {
stackOldest.push( stackNewest.pop() );
}
}
}
//look up the first element in queue
public T peek() {
shiftStacks();
return stackOldest.peek();
}
//remove the first element in queue
public T remove() {
shiftStacks();
return stackOldest.pop();
}
public static void main(String[] args){
MyQueue<Integer> m;
m = new MyQueue<Integer>();
m.add(1);
m.add(2);
m.add(3);
m.add(4);
m.add(5);
System.out.println(m.remove());
System.out.println(m.remove());
System.out.println(m.remove());
System.out.println(m.remove());
System.out.println(m.remove());
}
}