829.模擬佇列
阿新 • • 發佈:2020-10-12
實現一個佇列,佇列初始為空,支援四種操作:
(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≤100000,
1≤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; class Queue { public int[] q; public int hh; public int tt; public void init() { int N = 100010; q = new int[N]; // hh表示隊頭, tt表示隊尾 hh = 0; tt = -1; } public void push(int x) { q[++tt] = x; } public void pop() { hh++; } public int query() { return q[hh]; } public boolean isEmpty() { return hh > tt; } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Queue q = new Queue(); q.init(); int m = Integer.parseInt(sc.nextLine()); while ((m--) != 0) { String str = sc.nextLine(); String[] s = str.split(" "); if (s[0].equals("push")) { q.push(Integer.parseInt(s[1])); } else if (s[0].equals("pop")) { q.pop(); } else if (s[0].equals("empty")) { if (q.isEmpty()) { System.out.println("YES"); } else { System.out.println("NO"); } } else { System.out.println(q.query()); } } sc.close(); } }