使用棧實現隊列 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 top,?peek/pop from top,?size, 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.pswp.cn/news/394439.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394439.shtml
英文地址,請注明出處:http://en.pswp.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…