栈和队列相关算法题(Java)

所用示例均出自力扣https://leetcode-cn.com/
题解参考力扣和https://cyc2018.github.io/CS-Notes/#/notes/Leetcode 题解 - 目录1

用队列实现栈

思路:

  • 创建两个队列,一个用于输入in,一个用于输出out。
  • 添加的时候将数据加到in中,然后将out中的数据都加到in中,此时in队列的头就是刚压入的数。再将in, out互换,保证压入队列为空。
  • 对输出队列进行poll(),peek()等操作。

补:队列的相关操作

add         增加一个元索               如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove      移除并返回队列头部的元素     如果队列为空,则抛出一个NoSuchElementException异常
element     返回队列头部的元素          如果队列为空,则抛出一个NoSuchElementException异常
offer       添加一个元素并返回true      如果队列已满,则返回false
poll        移除并返问队列头部的元素     如果队列为空,则返回null
peek        返回队列头部的元素          如果队列为空,则返回null
put         添加一个元素               如果队列满,则阻塞
take        移除并返回队列头部的元素
class MyStack {
   
    private Queue<Integer> in;
    private Queue<Integer> out;
    /** Initialize your data structure here. */
    public MyStack() {
   
        in = new LinkedList<>();
        out = new LinkedList<>();
    }
    /** Push element x onto stack. */
    public void push(int x) {
   
        in.add(x);
        while(!out.isEmpty()){
   
            in.add(out.poll());
        }
        Queue temp = in;
        in = out;
        out = temp;
    }
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
   
        return out.poll();
    }
    /** Get the top element. */
    public int top() {
   
        return out.peek();
    } 
    /** Returns whether the stack is empty. */
    public boolean empty() {
   
        return out.isEmpty();
    }
}

  • 用一个队列实现,队列的压入是添加到队列尾部;
  • 每添加一个数字,就将该数的前size-1个数都取出,重新压入,这样就保证添加的数据在队列的头部;
  • 对给队列进行poll(),peek()操作。
class MyStack {
   
    private Queue<Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
   
        queue = new LinkedList<>();
    }
   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值