首页 > 其他 > 详细

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

时间:2016-02-29 19:59:30      阅读:152      评论:0      收藏:0      [点我收藏+]
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());
    }
    
    

}

 

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

原文:http://www.cnblogs.com/leehfly/p/5228626.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!