java JDK自带了队列对象,已经实现了队列,但是用java的jdk,哪还有什么意思呢?那直接使用队列不行了,这道题不就变成了你知道jdk怎么new一个队列吗?这样连简单题都算不上把。所以我觉得我应该自己实现一个队列的对象,使用数组来模拟这个队列。
思路:定一个队列对象,然后定义三个参数,一个是新增下标,一个是删除队列的下标,还有一个是判断队列空还是满的下标。队列是否满,其实只需要看最后一个下标就行了。
代码如下
package com.算法专练.牛客网.循环队列;
import java.util.Scanner;
/**
* @author xnl
* @Description:
* @date: 2022/5/27 20:10
*/
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 第一行的值, 下标0的值我们拿来初始化队列,下标1的值代表我们的操作数
String str = scanner.nextLine();
String[] split = str.split("\\s+");
MyQueue queue = new MyQueue(Integer.parseInt(split[0]));
for (int i = 0; i < Integer.parseInt(split[1]); i++) {
// 记录输入的值
String[] input = scanner.nextLine().split("\\s+");
String temp = input[0];
if (temp.equals("push")) {
queue.push(Integer.parseInt(input[1]));
} else if (temp.equals("pop")) {
queue.pop();
} else if (temp.equals("front")) {
queue.front();
} else {
return;
}
}
}
}
class MyQueue {
private int size;
private int[] queue;
private int index;
private int popIndex = 0;
private int diff;
public MyQueue() { }
public MyQueue(int size) {
this.size = size;
this.queue = new int[size];
this.index = 0; // 记录指针下标
this.diff = 0; // 差值
this.popIndex = 0;
}
private boolean isEmpty() {
return diff == 0 ;
}
public void push(int value) {
if (diff == size) {
System.out.println("full");
return;
}
queue[index] = value;
index = (index + 1) % size;
diff++;
}
public void pop() {
if (isEmpty()) {
System.out.println("empty");
return;
}
System.out.println(queue[popIndex]);
popIndex = (popIndex + 1) % size;
diff--;
}
public void front() {
if (isEmpty()) {
System.out.println("empty");
return;
}
System.out.println(queue[popIndex % size]);
}
}