基础算法面试题---如何用队列实现栈(1)

题目描述

如何用队列结构实现栈的push和pop操作。

队列和栈的概念

队列:先进先出,从头进,从尾出。

栈:先进后出,从头进,从头出。

解题思路

本题需要借助两个队列,通过让元素在两个队列中切换,来实现栈的功能。

假设分别有A、B两个队列,以及一个int类型的标识符F,当要添加元素时,如果F等于0,则添加到队列A中,否则添加到队列B中,
当要弹出元素时,如果F等于0,则先把队列A中的数据依次弹出并添加到队列B中,直到队列A中还剩最后一个元素时,则直接弹出,并设置F等于1,返回弹出元素。如果F等于1,则先把队列B中的数据依次弹出并添加到队列A中,直到队列B中还剩最后一个元素时,则直接弹出,并设置F等于0,返回弹出元素。

图解分析

1、假设现在要添加了3个元素,分别为:1,2,3
在这里插入图片描述

2、弹出一个元素

在这里插入图片描述

3、当又需要添加一个元素时。

在这里插入图片描述
4、当又要弹出一个元素时

在这里插入图片描述

5、如果继续需要弹出元素

在这里插入图片描述

代码实现

class MyStack {
    Queue<Integer> queue_one = new LinkedList<>();
    Queue<Integer> queue_two = new LinkedList<>();

    int flag = 0;

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

    }

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        if (flag == 0) {
            queue_one.add(x);
        } else {
            queue_two.add(x);
        }
    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
        if (flag == 0) {
            int size = queue_one.size();
            for (int i = 0; i < size - 1; i++) {
                queue_two.add(queue_one.poll());
            }
            flag = 1;
            return queue_one.poll();
        } else {
            int size = queue_two.size();
            for (int i = 0; i < size - 1; i++) {
                queue_one.add(queue_two.poll());
            }
            flag = 0;
            return queue_two.poll();
        }
    }

    /**
     * Get the top element.
     */
    public int top() {
        int i = 0;
        if (flag == 0) {
            Iterator<Integer> iterator = queue_one.iterator();
            while (iterator.hasNext()) {
                i = iterator.next();
            }
        } else {
            Iterator<Integer> iterator = queue_two.iterator();
            while (iterator.hasNext()) {
                i = iterator.next();
            }
        }
        return i;
    }

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

在当前方式下,如果要实现top方法,则需要遍历整个队列,并且直到遍历到最后一个元素时才能得到,在下一遍文章中,我们将通过另一种方式来优化它。基础算法面试题—如何用队列实现栈(2)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值