【剑指offer-Java版】07用两个栈实现队列

来源:互联网 发布:cf自瞄脚本源码 编辑:程序博客网 时间:2024/05/21 18:48

两个栈实现一个队列:stack_1 stack_2
入队操作:直接入stack_1
出队操作:如果stack_2不为空,那么从其中弹出一个作为出队元素,否则将stack_1元素全部依次压入stack_2然后弹出顶层

队满状态:stack_1和stack_2都满
队空状态:stack_1和stack_2都空

边界条件没有怎么考虑

    public class _Q07 {    private Stack<Integer> stack_1 = new Stack<>();    private Stack<Integer> stack_2 = new Stack<>();    public void enQueue(int val){        stack_1.push(val);    }    public int deQueue() throws Exception{        if(stack_2.isEmpty()){            while(!stack_1.isEmpty()){                stack_2.push(stack_1.pop());            }        }        if(stack_2.isEmpty()){            throw new Exception("no item in queue");        }        return stack_2.pop();    }    }

测试代码:

    public class _Q07Test extends TestCase {    _Q07 queue = new _Q07();    public void testQueue() throws Exception{        queue.enQueue(1);        queue.enQueue(3);        queue.enQueue(2);        queue.enQueue(4);        for(int i=0; i<4; i++){            System.out.println(queue.deQueue());        }    }    }
1 0