前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 232题用栈实现队列(Implement Queue using Stacks)

LeetCode 232题用栈实现队列(Implement Queue using Stacks)

作者头像
code随笔
发布2020-04-14 11:48:45
2230
发布2020-04-14 11:48:45
举报
文章被收录于专栏:code随笔的专栏code随笔的专栏

题目链接

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

题目描述

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

代码语言:javascript
复制
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;

再出栈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()无法完成,队为空。

代码

代码语言:javascript
复制
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随笔

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 code随笔 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接
  • 题目描述
  • 思路
  • 代码
  • 欢迎关注
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档