用两个栈实现队列,剑指offer P59

public class QueueByStack {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    public QueueByStack() {
        // TODO Auto-generated constructor stub
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }
    
    public void appendTail(Integer a) {
        stack1.push(a);
    }
    public Integer deleteHead() throws Exception{
        if(stack2.isEmpty()) {
            while(!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        if(stack2.isEmpty()) {
            throw new Exception("队列为空,不能删除");
        }
        return stack2.pop();
    }
    public static void main(String[] args) throws Exception {
        new QueueByStack();
        QueueByStack ququeByStack = new QueueByStack();
        ququeByStack.appendTail(1);
        ququeByStack.appendTail(2);
        System.out.println(ququeByStack.deleteHead());
    }
    
    

}

 

posted @ 2016-02-29 19:05  笨狗毒毒毒  阅读(130)  评论(0编辑  收藏  举报