码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-02-29 20:01:37      阅读:126      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!