循环队列
队列是一种先进先出的顺序存储结构,尾端进,头端出。这里我使用数组来实现循环队列的效果。
思路分析
首先定义一个数组,来存储数据。随后定义一个头指针front,指向队列的头元素;定义一个尾指针rear,指向待插入的位置,也就是队尾元素的后一个位置。 当头尾指针指向同一个位置时,即rear == front的时候,队列为空,这个好理解。当 (rear+1)%capacity == front时,队列为满。具体请看图解。
图解
线性看起来不直观,所以我又画了个环形的,请看下图。
代码实现
public class Test {
private int[] arr; // 数组实现循环队列
private int front; // 队列的头指针
private int rear; // 队列的尾指针
private int capacity; // 队列的最大容量
public Test(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
}
public int deQueue() { //出队操作
int value = arr[front];
front = (front + 1) % capacity;
return value;
}
public void enQueue(int ele) { //入队操作
if (isFull()) {
System.out.println("队列满,不能添加");
return;
}
arr[rear] = ele;
rear = (rear + 1) % capacity;
}
public boolean isFull() { //判断是否为满
return (rear + 1) % capacity == front;
}
public boolean isEmpty() { //判断是否为空
return rear == front;
}
public String toString() { //重写toString()方法
if (isEmpty()) {
return "队列为空,没有数据!";
}
StringBuilder sb = new StringBuilder();
sb.append("队头\n");
for (int x = front; x < front + getSize(); x++) {
sb.append("arr[").append(x % capacity).append("]=").append(arr[x % capacity]).append("\n");
}
sb.append("队尾");
return sb.toString();
}
public int getSize() { //获取队列中实际存储的位置
return (rear - front + capacity) % capacity;
}
public static void main(String[] args) {
Test test = new Test(4);
test.enQueue(6); //入队
test.enQueue(7);
test.enQueue(8);
System.out.println("***********入队后************");
System.out.println(test);
test.deQueue();//出队
test.deQueue();
System.out.println("***********出队后************");
System.out.println(test);
System.out.println("***********入队后************");
test.enQueue(9);
test.enQueue(10);
System.out.println(test);
test.deQueue();
System.out.println("***********出队后************");
System.out.println(test);
}
}