import java.util.NoSuchElementException;
import java.util.Stack;
/**
* 自定义的队列:利用两个栈来实现队列的add和remove功能
*/
public class CustomQueue<T> {
public Stack<T> pushStack = new Stack<T>();
public Stack<T> popStack = new Stack<T>();
/**
* 向队列的尾部插入元素
*
* @param obj
*/
public void add(T obj) {
pushStack.push(obj);
}
/**
* 将队列的头元素删除
*
* @return
*/
public T remove() {
if (popStack.isEmpty()) {
while (!pushStack.isEmpty()) {
T top = pushStack.pop();
popStack.push(top);
}
}
if (popStack.isEmpty()) {
throw new NoSuchElementException();
}
T obj = popStack.pop();
System.out.println("delete:" + obj);
return obj;
}
public static void main(String[] args) {
CustomQueue<String> queue = new CustomQueue<>();
queue.add("a");
queue.add("b");
queue.add("c");
queue.remove();
queue.remove();
queue.add("d");
queue.remove();
queue.remove();
}
}