剑指offer面试题java实现之题7之相关题目:用两个队列实现一个栈

来源:互联网 发布:啄木鸟审计软件 编辑:程序博客网 时间:2024/06/06 10:52
/** * 使用两个队列模拟栈操作 * @author Administrator * */public class StackWithTwoQueue<T> {    Queue<T> queue1 = new LinkedList<T>();    Queue<T> queue2 = new LinkedList<T>();    /**     *模拟入栈操作     */    public void push(T t){        if(queue1.size()>0)            queue1.add(t);        else            queue2.add(t);    }    /**     * 模拟出栈操作     * @return     */    public T pop(){        /*选择不为空的那个队列,然后将所有元素(除队尾元素外),         * 移动到另一个队列中,接着进行出栈操作         * */        if(queue1.size()>queue2.size()){            while(queue1.size()!=1){                queue2.add(queue1.remove());            }            return queue1.remove();//出栈操作        }else if(queue2.size()>queue1.size()){            while(queue2.size()!=1){                queue1.add(queue2.remove());            }            return queue2.remove();//出栈操作        }else{//此情况为两个队列全部为空            try {                throw new Exception("栈为空,不能出栈");            } catch (Exception e) {                e.printStackTrace();            }            return null;        }    }    public static void main(String[] args) {    StackWithTwoQueue<Integer> stack = new StackWithTwoQueue<Integer>();        stack.push(1);        stack.push(2);        stack.push(3);        System.out.println(stack.pop());        stack.push(4);        stack.push(5);        System.out.println(stack.pop());        System.out.println(stack.pop());        System.out.println(stack.pop());    }}
0 0
原创粉丝点击