实现循环链表的难点在于, 当front和rear指向同一个位置时,这代表的是队空还是队满呢?
解决这种问题的常见做法是这种:
方法一 : 使用一标记,用以区分这样的易混淆的情形, 重新定义一个变量, 用于存储队列中数据个数。
方法二 : 牺牲一个元素空间。当front和rear相等时,为空。当rear的下一个位置是front时。为满
?代码实现 :?
package dataStructure.circleArray;
import java.lang.reflect.Array;
/**
* @author hctrl
* @date 2021/8/12 20:14
*/
public class CircleArray<T> {
private Integer size;
private Integer front;
private Integer rear;
private T[] arr;
public CircleArray(Class<T> type, int length) {
this.size = length;
arr = (T[]) Array.newInstance(type, length);
front = 0;
rear = 0;
}
//判断数组是否满了
public boolean isFull() {
return (rear + 1) % size == front;
}
//判断数组是否为空
public boolean isEmpty() {
return front == rear;
}
//入队列
public void push(T t) {
//判断队列是否已经满了
if (isFull()) {
System.out.println("队列已经满了===========");
return;
}
arr[rear] = t;
rear = (rear + 1) % size;
}
//出队列
public void poll() {
System.out.println(arr[front]);
if (isEmpty()) {
System.out.println("队列为空=====================");
return;
}
front = (front + 1) % size;
}
//查看队列中的全部元素 (rear + maxSize - front) % maxSize
public void showAll() {
int count = (rear + size - front) % size;
for (int i = front; i < front + count; i++) {
System.out.printf("arr[%d] = %d\n", i % size, arr[i % size]);
}
}
}
?测试类 :?
package dataStructure.circleArray;
import java.util.Scanner;
/**
* @author hctrl
* @date 2021/8/12 20:14
*/
public class CircleArrayTest {
public static void main(String[] args) {
CircleArray<Integer> circleArray = new CircleArray<>(Integer.class,7);
boolean loop = true;
while (loop){
System.out.println("=======================================================");
System.out.println("push: 入队");
System.out.println("poll: 出队");
System.out.println("show: 查看全部数据");
System.out.println("=======================================================");
Scanner scanner = new Scanner(System.in);
String choose = scanner.next();
switch (choose){
case "push":
System.out.println("请输入入队的数据==============");
Scanner scanner1 = new Scanner(System.in);
int i = scanner1.nextInt();
circleArray.push(i);
break;
case "poll":
circleArray.poll();
break;
case "show":
circleArray.showAll();
break;
default:
loop = false;
break;
}
}
}
}
?
|