實作一個佇列,佇列初始為空,支持四種操作:
(1) “push x” – 向隊尾插入一個數x;
(2) “pop” – 從隊頭彈出一個數;
(3) “empty” – 判斷佇列是否為空;
(4) “query” – 查詢隊頭元素,
現在要對佇列進行M個操作,其中的每個操作3和操作4都要輸出相應的結果,
輸入格式
第一行包含整數M,表示操作次數,
接下來M行,每行包含一個操作命令,操作命令為”push x”,”pop”,”empty”,”query”中的一種,
輸出格式
對于每個”empty”和”query”操作都要輸出一個查詢結果,每個結果占一行,
其中,”empty”操作的查詢結果為“YES”或“NO”,”query”操作的查詢結果為一個整數,表示隊頭元素的值,
資料范圍
1≤M≤1000001≤M≤100000,
1≤x≤1091≤x≤109,
所有操作保證合法,
輸入樣例:
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
輸出樣例:
NO 6 YES 4
佇列先入先出
代碼:
import java.util.Scanner; public class Main{ static final int max=(int)1e5+5; static int que[]=new int[max]; static int h=0,q=1; public static void main(String[] args) { Scanner scan=new Scanner(System.in); int m=scan.nextInt(); while(m-->0){ String s=scan.next(); if(s.equals("push")){ int x=scan.nextInt(); que[++h]=x; } else if(s.equals("query")){ System.out.println(que[q]); } else if(s.equals("pop")){ q++; } else if(s.equals("empty")){ if(h<q) System.out.println("YES"); else System.out.println("NO"); } } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/103937.html
標籤:其他
上一篇:827. 雙鏈表
下一篇:830. 單調堆疊
