LeetCode 232题用栈实现队列(Implement Queue using Stacks) Java语言求解

题目链接

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

题目描述

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

思路

使用两个栈来完成操作,首先全部进入第一个栈,再全部进入第二个栈,用图来演示一下:
首先进入栈1;

入栈1

然后出栈1,入栈2;
出栈1入栈2
再出栈2。
出栈2

由图可以知道,用两个栈即可完成队列的操作;

分为下面三种情况

  1. Stack_1空,Stack_2有元素,这时push()操作让Stack_1进行push();pop()操作,只需让Stack_2进行pop();peek()操作,也只需让Stack_2进行peek()就可以了;这时队列不为空;
  2. Stack_1不空,Stack_2空,这时push()操作让Stack_1进行push();pop()操作需要将Stack_1的所有元素进入Stack_2,Stack_2进行pop();peek()操作,也只需要将Stack_1的所有元素进入Stack_2,再让Stack_2进行peek()就可以了;这是队列不为空;
  3. Stack_1空,Stack_2也为空,push()操作让Stack_1进行push()即可,pop()和push()无法完成,队为空。

代码

import java.util.Stack;

class MyQueue {

    //初始化栈1和栈2
    private Stack<Integer> Stack_1;
    private Stack<Integer> Stack_2;
    /** Initialize your data structure here. */
    public MyQueue() {
        Stack_1 = new Stack<>();
        Stack_2 = new Stack<>();
    }
    //进入第一个栈
    /** Push element x to the back of queue. */
    public void push(int x) {
        Stack_1.push(x);
    }
    

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        //如果栈2是空的
        if(Stack_2.isEmpty()){
            //将栈1的所有元素入栈2
            while(!Stack_1.isEmpty()){
                Stack_2.push(Stack_1.pop());
            }
        }
        if (!Stack_2.isEmpty()) {
            return Stack_2.pop();
        }
        throw new RuntimeException("MyQueue空了!");
    }

    /** Get the front element. */
    public int peek() {
        //如果栈2是空的
        if(Stack_2.isEmpty()){
            //将栈1的所有元素入栈2
            while(!Stack_1.isEmpty()){
                Stack_2.push(Stack_1.pop());
            }
        }

        if (!Stack_2.isEmpty()) {
            return Stack_2.peek();
        }
        throw new RuntimeException("MyQueue空了!");

    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return Stack_1.isEmpty() && Stack_2.isEmpty();
    }
}

欢迎关注

扫下方二维码即可关注:,微信公众号:code随笔
微信公众号:code随笔

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

随机的未知

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

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

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

打赏作者

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

抵扣说明:

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

余额充值