標籤:alt style scan opera [] port .com 第一個 ref
目錄
1 問題描述
2 解決方案
1 問題描述問題描述 隊列操作題。根據輸入的操作命令,操作隊列(1)入隊、(2)出隊並輸出、(3)計算隊中元素個數並輸出。輸入格式 第一行一個數字N。
下面N行,每行第一個數字為操作命令(1)入隊、(2)出隊並輸出、(3)計算隊中元素個數並輸出。輸出格式 若干行每行顯示一個2或3命令的輸出結果。注意:2.出隊命令可能會出現空隊出隊(下溢),請輸出“no”,並退出。範例輸入7
1 19
1 56
2
3
2
3
2範例輸出19
1
56
0
no資料規模和約定 1<=N<=50 2 解決方案
特別注意:注意:2.出隊命令可能會出現空隊出隊(下溢),請輸出“no”,並退出。
具體代碼如下:
import java.util.ArrayList;import java.util.Scanner;public class Main { public void printResult(int[][] operation) { ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0;i < operation.length;i++) { if(operation[i][0] == 1) list.add(operation[i][1]); else { if(operation[i][0] == 2) { if(list.size() == 0) { System.out.println("no"); return; //注意,此時題意要求直接退出 } else { System.out.println(list.get(0)); list.remove(0); } } else if(operation[i][0] == 3) { System.out.println(list.size()); } } } return; } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); int n = in.nextInt(); if(n < 1 || n > 50) return; int[][] operation = new int[n][2]; for(int i = 0;i < n;i++) { int a = in.nextInt(); if(a == 1) { int b = in.nextInt(); operation[i][0] = a; operation[i][1] = b; } else { operation[i][0] = a; } } test.printResult(operation); }}
演算法筆記_080:藍橋杯練習 隊列操作(Java)