题解 | #【模板】队列#
【模板】队列
https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.nextLine()); MyQueue q = new MyQueue(n); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str[] = in.nextLine().split(" "); if(str[0].equals("push")){ q.push(str[1]); } if(str[0].equals("pop")){ q.pop(); } if(str[0].equals("front")){ q.front(); } } } } class MyQueue{ int front; int tail; int size; String [] nums; MyQueue(int size){ this.front = -1; this.tail = -1; this.size = size; nums = new String[size]; } public void pop(){ if(this.front == this.tail){ System.out.println("error"); }else{ this.front = (this.front + 1)%this.size; System.out.println(nums[this.front]); } } public void push(String num){ if(this.front != (this.tail + 1)%this.size){ this.tail = (this.tail + 1)%this.size; nums[this.tail] = num; } } public void front(){ if(this.front == this.tail){ System.out.println("error"); }else{ System.out.println(nums[(this.front + 1)%this.size]); } } }