题解 | #【模板】循环队列#
【模板】循环队列
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);
String s[] = in.nextLine().split(" ");
int n = Integer.parseInt(s[0]);
MyQueue q = new MyQueue(n+1);
// 注意 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 = 0;
this.tail = 0;
this.size = size;
nums = new String[size];
}
public void pop() {
if (this.front == this.tail) {
System.out.println("empty");
} 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) {
System.out.println("full");
}else{
this.tail = (this.tail + 1) % this.size;
nums[this.tail] = num;
}
}
public void front() {
if (this.front == this.tail) {
System.out.println("empty");
} else {
System.out.println(nums[(this.front + 1) % this.size]);
}
}
}

查看19道真题和解析
海康威视公司福利 1154人发布