LeetCode.232 用栈实现队列

原题

https://leetcode-cn.com/problems/implement-queue-using-stacks/

在这里插入图片描述

思路

定义两个栈,一个in,一个out
in:用于数据入队,队列的push方法直接入到该栈中
out:用于数据出队,队列的poppeek方法直接从该栈中取数据
注意:此时需要考虑多次操作,例如:添加 -> 取完 -> 添加 -> 取值


题解

package com.leetcode.code;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Description:
 * @ClassName: Code232
 * @Author: ZK
 * @Date: 2021/3/5 23:38
 * @Version: 1.0
 */
public class Code232 {

//    定义两个双端队列:是一种具有队列和栈的性质的数据结构。
    Deque<Integer> in;
    Deque<Integer> out;

    public Code232() {
        in = new LinkedList<>();
        out = new LinkedList<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
//        直接添加到in栈中
        in.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
//        判断out栈中是否存在元素
        if (out.isEmpty()) {
//            如果不存在,则将in栈中的所有元素都添加到out栈中
            twiceDeal();
        }
//        直接弹出out栈中的栈顶元素
        return out.pop();
    }

    /** Get the front element. */
    public int peek() {
//        判断out栈中是否存在元素
        if (out.isEmpty()) {
//            如果不存在,则将in栈中的所有元素都添加到out栈中
            twiceDeal();
        }
//        直接获取out栈中的栈顶元素
        return out.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
//        判断out栈是否为空,同时需判断in栈中是否存在元素
//        in栈中如果存在元素,说明有数据添加进来未弹出
        return out.isEmpty() && in.isEmpty();
    }

    /**
     * 将in栈中的元素全部添加到out栈中
     */
    private void twiceDeal(){
        while(!in.isEmpty()){
            out.push(in.pop());
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

难过的风景

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

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

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

打赏作者

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

抵扣说明:

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

余额充值