使用栈实现队列 Implement Queue using Stacks

为什么80%的码农都做不了架构师?>>>   hot3.png

问题:

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is emptyoperations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

解决:

【注】关于测试参数的解释:

["MyQueue","push","push","peek","pop","pop","empty"] --- 表示要进行的操作

[[],[1],[2],[],[],[],[]] --- 表示对应传入的参数

① 使用两个栈s1,s2,进栈的时候不做任何处理,出栈的时候把栈逆序放在另外一个栈,出另外一个栈。
之前写经常出现空栈异常或者超时,就是没有写好s1,s2之间的转换。

class MyQueue { // 87ms
    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    /** Initialize your data structure here. */
    public MyQueue() {}
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(! s2.isEmpty()) s1.push(s2.pop());
        s1.push(x);

    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(! s1.isEmpty()) s2.push(s1.pop());
        return s2.pop();

    }
    /** Get the front element. */
    public int peek() {
        while(! s1.isEmpty()) s2.push(s1.pop());
        return s2.peek();
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        while(! s2.isEmpty()) s1.push(s2.pop());
        return s1.isEmpty();

    }
}
/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

② 使用两个栈,在进栈的时候,把栈逆序放在另外一个栈,出的时候直接出另外一个栈就可以了。

class MyQueue { //93ms
    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    /** Initialize your data structure here. */
    public MyQueue() {}
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(! s1.isEmpty()) s2.push(s1.pop());
        s2.push(x);
        while(! s2.isEmpty()) s1.push(s2.pop());

    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return s1.pop();
    }
    /** Get the front element. */
    public int peek() {
        return s1.peek();
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.isEmpty();
    }
}

③ 除了使用两个栈之外,额外使用一个指针指向头部。

class MyQueue { //113ms
    Stack<Integer> s1 = new Stack<>();
    Stack<Integer> s2 = new Stack<>();
    int head;
    /** Initialize your data structure here. */
    public MyQueue() {}
    /** Push element x to the back of queue. */
    public void push(int x) {
        if(s1.isEmpty()) head = x;
        s1.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(! s1.isEmpty()) s2.push(s1.pop());
        int top = -1;
        if(! s2.isEmpty()){
            top = s2.pop();
            if(! s2.isEmpty()) head = s2.peek();
        }
        while(! s2.isEmpty()) s1.push(s2.pop());
        return top;
    }
    /** Get the front element. */
    public int peek() {
        return head;
    }
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.isEmpty();
    }
}

转载于:https://my.oschina.net/liyurong/blog/1512615

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394439.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java利用POI生成Excel强制换行

前一段时间在做一个学校排课系统时&#xff0c;有一个地方需要利用把课程表生成excel汇出给客户&#xff0c;由于之前用excel都只是简单的应用&#xff0c;在单元格里都是用自动换行&#xff0c;而这次可能需要用到手动强制换行。 于是我在网上找了一下&#xff0c;网上找到的文…

550什么意思_研报翻译官第二期:带你了解什么是CPI

欢迎收看“第二期”研报翻译官&#xff0c;临近年末&#xff0c;各类金融研报接踵而至&#xff0c;我们也常会看到GDP、CPI、PPI这类字眼。过年回家跟亲戚朋友唠嗑的时候&#xff0c;如果不扯上几句CPI或PPI&#xff0c;都显自己得不够专业。听你们吹牛&#xff0c;我炒菜都有劲…

leetcode1314. 矩阵区域和(动态规划)

给你一个 m * n 的矩阵 mat 和一个整数 K &#xff0c;请你返回一个矩阵 answer &#xff0c;其中每个 answer[i][j] 是所有满足下述条件的元素 mat[r][c] 的和&#xff1a; i - K < r < i K, j - K < c < j K (r, c) 在矩阵内。 示例 1&#xff1a; 输入&…

python读取数据库文件的扩展名_Python读取sqlite数据库文件的方法分析

本文实例讲述了Python读取sqlite数据库文件的方法。分享给大家供大家参考&#xff0c;具体如下&#xff1a;这是Python内置的&#xff0c;不需要pip install 包数据库里面有很多张表要操作数据库首先要连接conect数据库然后创建游标cursor来执行execute&#xff33;&#xff31…

C# 文件异步操作

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO;//文件异步操作 namespace FileAsynchronousOperation {class Program{static void Main(string[] args){//实例化MyFile类MyFile myF…

软考 中级职称哪些最热门_我如何利用有史以来最热门的中级故事来建立排行榜。 以及它几乎是怎么死的。...

软考 中级职称哪些最热门by Michael Deng邓小平 我如何利用有史以来最热门的中级故事来建立排行榜。 以及它几乎是怎么死的。 (How I built a leaderboard with the top Medium stories of all time. And how it almost died.) Last year I built Top Medium Stories — a web…

面试题一

1.html页面由标签组成&#xff0c;请写出<head>中脚本定义标签、下拉选择框标签  脚本定义标签&#xff1a;<javascript></javascript>   下拉框选择标签&#xff1a;<select><option values""></option></select> 2…

leetcode712. 两个字符串的最小ASCII删除和(动态规划)-Gogo

给定两个字符串s1, s2&#xff0c;找到使两个字符串相等所需删除字符的ASCII值的最小和。 示例 1: 输入: s1 “sea”, s2 “eat” 输出: 231 解释: 在 “sea” 中删除 “s” 并将 “s” 的值(115)加入总和。 在 “eat” 中删除 “t” 并将 116 加入总和。 结束时&#xff0…

python中封装是什么意思_Python中数据封装是什么?

封装——“隐藏一切可以隐藏的实现细节&#xff0c;只向外界暴露(提供)简单的编程接口”。在上节的 Student 类中&#xff0c;每个实例就拥有各自的 name 和 age 这些数据。我们可以通过函数来访问这些数据&#xff0c;比如打印一个学生的年龄&#xff1a;>>> def pri…

jieba库的使用

jieba库的使用: jieba库是一款优秀的 Python 第三方中文分词库&#xff0c;jieba 支持三种分词模式&#xff1a;精确模式、全模式和搜索引擎模式&#xff0c;下面是三种模式的特点。 精确模式&#xff1a;试图将语句最精确的切分&#xff0c;不存在冗余数据&#xff0c;适合做文…

Go语言实现HashSet

set.go // set project set.go package settype Set interface {Add(e interface{}) boolRemove(e interface{})Clear()Contains(e interface{}) boolLen() intSame(other Set) boolElements() []interface{}String() string }// 将集合other添加到集合one中 func AddSet(one S…

c#控件弹幕效果_C# Form 实现桌面弹幕

使用C# Form 简单的实现了弹幕效果1.创建一个Form 设置2.添加一个计时器3. 代码using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Drawing.Text;using System.Linq;using System.Text;using S…

Makefile中怎么使用Shell if判断

/********************************************************************** Makefile中怎么使用Shell if判断* 说明&#xff1a;* 譬如可能会在Makfile中需要判断文件、文件夹的存在&#xff0c;使用shell语法* 输出一些信息&#xff0c;等等。** …

我如何使用React和Typescript在freeCodeCamp中构建天气应用

by Kelvin Mai通过凯文麦 我如何使用React和Typescript在freeCodeCamp中构建天气应用 (How I built the weather app in freeCodeCamp using React and Typescript) So I finally decided to come back to freeCodeCamp and try to finish out my Front End Development Certi…

mysql结果集相减_MySQL_(Java)使用JDBC向数据库发起查询请求

课程相关链接&#xff1a;JDBC编程和MySQL数据库课程源代码在文章末尾~Java Database Connectivity简单来说就是使用Java里面提供的一些类和方法&#xff0c;利用程序链接数据库&#xff0c;进行增删改查操作。这个过程就叫做JDBC编程接下来我们便分五步通过JDBC对MySQL中的数据…

在双系统(Windows与Ubuntu)下删除Ubuntu启动项

问题概述&#xff1a;因为在自己学习Linux的时候&#xff0c;按照网上的教程错误的删除了Ubuntu的一个内核驱动&#xff0c;导致Ubuntu不能启动。我想到的办法是重新安装系统&#xff0c;重装系统的第一步便是将Ubuntu从电脑中卸载。该笔记是有关如何删除Ubuntu启动项的。 使用…

iangularjs 模板_2018-web前端的自我介绍-优秀word范文 (5页)

本文部分内容来自网络整理&#xff0c;本司不为其真实性负责&#xff0c;如有异议或侵权请及时联系&#xff0c;本司将立即删除&#xff01;本文为word格式&#xff0c;下载后可方便编辑和修改&#xff01;web前端的自我介绍篇一&#xff1a;个人总结的web前端面试题1、自我介绍…

Teradata QueryGrid整合最佳分析技术 拓展客户选择空间

ZDNET至顶网CIO与应用频道 05月11日 北京消息&#xff1a; 为持续帮助企业克服数据散布在不同分析系统的困难&#xff0c;全球领先的大数据分析和营销应用服务供应商Teradata天睿公司宣布对Teradata QueryGrid 进行重要技术升级。此次升级新增并强化六项QueryGrid技术&#xf…

神舟笔记本bios_海尔雷神(蓝天)神舟战神游戏本风扇狂转掉电大写灯狂闪维修实例...

昨天收到一台网友寄过来的海尔雷神游戏本。说到这个游戏本品牌&#xff0c;其实有几个品牌的笔记本&#xff0c;它们的主板和模具是一模一样的&#xff0c;也就是我们看到的品牌log不一样而已。比如神舟的战神 &#xff0c;机械师&#xff0c;机械革命&#xff0c;麦本本等等。…

Oracle 学习----:查看当前时间与Sqlserver语句不一样了

oracle:select sysdate from dual sqlserver: select getdate() ---------------------试试这个---------------------------------------------------------- insert into OracleTab values(sysdate) insert into SqlserverTab values(getdate())转载于:https://www.cnblogs…