题解 | 【模板】循环队列
【模板】循环队列
https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=0, q=0; // 注意 hasNext 和 hasNextLine 的区别 if(in.hasNextLine()){ String line = in.nextLine(); String []arr = line.split(" "); n = Integer.parseInt(arr[0]); q = Integer.parseInt(arr[1]); } Queue queue = new Queue(n); while ((q-- > 0) && in.hasNextLine()) { String line = in.nextLine(); String[] arr = line.split(" "); String operation = arr[0]; try { if (operation.equals("push")) { queue.push(Integer.parseInt(arr[1])); } else if (operation.equals("pop")) { System.out.println(queue.pop()); } else if (operation.equals("front")) { System.out.println(queue.front()); } else { System.out.println("其他的非法操作"); } } catch (RuntimeException e) { //e.printStackTrace(); System.out.println(e.getMessage()); } } } } class Queue { int[] arr; int index = -1; Queue() { arr = new int[16]; } Queue(int n) { arr = new int[n]; } public void push(int x) { if (index + 2 > arr.length) { throw new RuntimeException("full"); } arr[++index] = x; } public String front() { if (index == -1) { throw new RuntimeException("empty"); } return Integer.toString(arr[0]); } public String pop() { if (index == -1) { throw new RuntimeException("empty"); } String top = Integer.toString(arr[0]); for (int i = 1; i <= index; ++i) { arr[i - 1] = arr[i]; } index -= 1; return top; } }