【ZJOF】用来个栈来实现一个队列

191 阅读1分钟

题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail 和deleteHead,
分别完成在队列尾部插入结点和在队列头部删除结点的功能
public class NList<T>{
    private Stack<T> stack1=new Stack<>();
    private Stack<T> stack2=new Stack<>();

    public void appendTail(T value){
        stack1.add(value);
    }

    public T deleteTail() throws Exception {
        if (stack2.isEmpty()){
            if (stack1.isEmpty()){
                throw new Exception("the queue is no element");
            }else {
                for (T element:stack1){
                    stack2.add(element);
                }
            }
        }
        return stack2.pop();
    }
}