Java使用一个或两个队列快速实现堆栈的方法

出自LeetCode225:只是用队列的offer、poll、isEmpty方法实现一个堆栈的存取。

其基本原理都是通过对出入队列的元素顺序进行逆向处理,由于java中可以用LinkedList来实现队列,因此在每次往队列中添加一个新元素时,都可以通过循环来将此元素移动到末尾,这样实现先进后出的特性。

1.使用一个队列实现

class MyStack {

    Queue<Integer> queue;
    
    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.offer(x);
        for(int i = 1; i < queue.size(); i++)
            queue.offer(queue.poll());
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.size() == 0;
    }
}

2.使用两个队列实现 

此方法时刻保证a队列为空,在每次往a队列中添加元素时,新入的元素始终在队首,通过b队列将之前入队的元素逆序存入a队列中实现堆栈效果(即b队列中的元素顺序始终是和a队列offer的元素顺序相逆的)

class MyStack {
    Queue<Integer> a;
    Queue<Integer> b;

    /**
     * Initialize your data structure here.
     */
    public MyStack() {
        a = new LinkedList<>();
        b = new LinkedList<>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        a.offer(x);
        while (!b.isEmpty())
        {
            a.offer(b.poll());
        }
        Queue tmp = a;
        a = b;
        b = tmp;
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return b.poll();
    }

    /** Get the top element. */
    public int top() {
        return b.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return b.isEmpty();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值