用两个队列实现栈

 基本思路
     队列是只能进行先进先出结构的,而栈是先进后出结构的
     队列实现栈:思路是有两个队列,一个用来存放数据,一个用来作为辅助,两个队列循环使用。
     当add()时,数据直接压入到数据队列中去就行
     当pop()时,需要取出的数据是数据队列的尾部数据,显然直接取出是不可行的
     这时,我们借助一个辅助队列,先将数据队列中的所有数据,除了最后一个数据外,都放入辅助队列中,然后再将最后一个数据弹出
     最后。我们再将辅助队列中的数据全部放入数据队列中去
     就实现了队列的pop()操作

     当top()时,和pop()有一点小差别,就把数据队列的最后一个数据记录下来,最后作为返回值返回就行。

     当empty()时,只需要判断俩队列是否都为empty()就行
class MyStack {

    //使用两个队列的轮流使用,始终保持一个队列为空,一个队列为数据队列,一个队列为辅助队列。
    LinkedList<Integer> queue1 = new LinkedList<>();
    LinkedList<Integer> queue2 = new LinkedList<>();

    /** Initialize your data structure here. */
    public MyStack() {

    }
    
    //只需要将只插入到数据队列中去就行
    /** Push element x onto stack. */
    public void push(int x) {
        if(queue1.isEmpty()){
            queue2.offer(x);
        }else{
            queue1.offer(x);
        }
    }

    //将数据队列的值放入辅助队列,除最后一个数据,记录下来,作为返回值,其余的放入辅助队列中,这个时候辅助队列成为了数据队列
    //这就是我们之前所说的两个队列循环使用,始终保持一个队列为null
    //有什么好处呢?
    //当进行pop()操作的时候,需要将数据队列的值转移到辅助队列中去,这样才能取到数据队列中的队尾值
    //如果数据队列还想继续成为数据队列的角色的话,就得继续将辅助队列的值放入数据队列中去,显然,十分麻烦
    //所以我们将这两个队列循环使用,避免不必要的操作
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {

        if(queue1.isEmpty()){
            while(queue2.size()>1){
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }else{
            while(queue1.size()>1){
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }
    }

    //和pop()差不多,我们只需要将数据队列的最后一个数据取出并返回就行
    /** Get the top element. */
    public int top() {
        int top = 0;
        if(queue1.isEmpty()){
            while(queue2.size()>1){
                queue1.offer(queue2.poll());
            }
            top = queue2.poll();
            queue1.offer(top);
        }else{
            while(queue1.size()>1){
                queue2.offer(queue1.poll());
            }
            top =  queue1.poll();
            queue2.offer(top);
        }
        return top;
    }
    
    //判断俩队列都是否为emtpy
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值