用队列实现栈:简单题三十五题JAVA

该博客介绍了一种利用两个队列实现栈的方法。在Java中,通过一个队列进行压栈操作,另一个队列用于出栈和查看栈顶元素。在压栈时,将新元素放入第二个队列,并将第一个队列的所有元素转移到第二个队列。当需要出栈或查看栈顶元素时,直接从第一个队列进行操作。这个实现充分利用了队列的FIFO特性,简化了栈的操作。
摘要由CSDN通过智能技术生成

用队列实现栈

在这里插入图片描述

public class T35 {

    //两个队列实现栈 一个负责压栈 出栈
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    /** Initialize your data structure here. */
    public T35() {
        queue1 = new LinkedList();
        queue2 = new LinkedList();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        //offer() 添加在链表下一位 方法只会返回 false
        queue2.offer(x);
        while (!queue1.isEmpty()) {
            //poll()都是用来从队列头部删除一个元素,poll() 方法只会返回 null 。
            queue2.offer(queue1.poll());
        }
        //交换2个 队列(链表)的值
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }


    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        //poll()都是用来从队列头部删除一个元素,poll() 方法只会返回 null 。
        return queue1.poll();
    }

    /** Get the top element. */
    public int top() {
        //返回头部数据
        return queue1.peek();
    }

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

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一只小小狗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值