用两个队列实现栈,java代码实现

62 篇文章 0 订阅

原文:用两个队列实现栈,java代码实现

1 实现原理介绍

队列和栈的功能在用两个栈实现队列,java代码实现这边文章中已经介绍过了,这里就不多说了,直接讲实现原理:

当需要插入元素时,总是将新元素插入到那个空的队列中,然后再将另一个有数据的队列中的数据,取出插入到存放新元素的队列中,即可完成栈的功能。**注意,每次执行完一次操作,两个队列中,只有一个队列有数据,要么是A,要么是B。**下面画图介绍具体过程:

  • 插入元素1

直接插入到队列A

此时有数据的是队列A

  • 插入元素2

第一步

第二步,腾入队列A

此时有数据的是队列B

  • 插入元素3

第一步,插入新元素

第二步,腾入队列A

此时有数据的队列A

  • 删除栈顶元素,pop操作

直接使用队列删除非空队列队首元素

2 java代码实现

import java.util.LinkedList;
import java.util.Queue;

public class QueueToStack {
    public static void main(String[] args) {
        QueueToStack queueToStack = new QueueToStack();
        queueToStack.push(1);
        queueToStack.push(2);
        queueToStack.push(3);
        queueToStack.push(4);
        queueToStack.pop();
        int data = queueToStack.top();
        System.out.println(data);
        System.out.println(queueToStack.empty());
    }

    Queue<Integer> queueA = new LinkedList<>();
    Queue<Integer> queueB = new LinkedList<>();

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        if (queueA.isEmpty() && !queueB.isEmpty()) {
            queueA.add(x);
            while (!queueB.isEmpty()){
                int data = queueB.remove();
                queueA.add(data);
            }

        } else if (!queueA.isEmpty() && queueB.isEmpty()) {
            queueB.add(x);
            while (!queueA.isEmpty()){
                int data = queueA.remove();
                queueB.add(data);
            }

        } else if (queueA.isEmpty() && queueB.isEmpty()) {
            queueA.add(x);
        }
    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
        if (queueA.isEmpty() && !queueB.isEmpty())
            return queueB.remove();
        return queueA.remove();

    }

    /**
     * Get the top element.
     */
    public int top() {
        if (queueA.isEmpty() && !queueB.isEmpty())
            return queueB.peek();
        return queueA.peek();
    }

    /**
     * Returns whether the stack is empty.
     */
    public boolean empty() {
        if (queueA.isEmpty() && queueB.isEmpty())
            return true;
        return false;
    }
}

运行结果:

运行结果

写在最后

欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。
微信公众号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值