环形队列
Posted bingbug
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了环形队列相关的知识,希望对你有一定的参考价值。
当队列尾部插入元素满了,头部又删掉了一些元素,这种情况下,就会误认为已满无法存入数据,而实际上头部删除了元素已经留出了空间。
这时候环形队列就解决了这样的一个问题,环形队列的 front 指针始终指向当前队列的第一个元素;rear 指针始终指向最后一个元素后一个的位置(也可以理解为第一个元素的前一个位置为)
队列满条件 ( rear + 1 ) % maxSize = font
队列空条件 rear = font
队列有效数据个数 ( rear + maxSize - front) % maxSize
package queue; import java.util.Scanner; public class CircleArrayQueueDemo { public static void main(String[] args) { CircleArray arrayQueue = new CircleArray(4); char key = ‘ ‘; Scanner scanner = new Scanner(System.in); boolean loop = true; while (loop) { System.out.println("s 显示队列"); System.out.println("e 退出程序"); System.out.println("a 添加数据到队列"); System.out.println("g 从队列取出数据"); System.out.println("h 查看队列头数据"); key = scanner.next().charAt(0); switch (key) { case ‘s‘: arrayQueue.showQueue(); break; case ‘e‘: scanner.close(); loop = false; break; case ‘a‘: System.out.println("请输入"); int value = scanner.nextInt(); arrayQueue.addQueue(value); break; case ‘g‘: try { int res = arrayQueue.getQueue(); System.out.printf("取出数据为%d ", res); } catch (Exception e) { System.out.println(e.getMessage()); } break; case ‘h‘: try { int res = arrayQueue.headQueue(); System.out.printf("队列头数据为%d ", res); } catch (Exception e) { System.out.println(e.getMessage()); } break; } System.out.println("程序退出"); } } } class CircleArray { private int maxSize; private int front; private int rear; private int[] arr; public CircleArray(int arrMaxSize) { maxSize = arrMaxSize; arr = new int[maxSize]; } public boolean isFull() { return (rear + 1) % maxSize == front; } public boolean isEmpty() { return rear == front; } public void addQueue(int n) { if (isFull()) { System.out.println("队列已满"); return; } arr[rear] = n; rear = (rear + 1) % maxSize; } public int getQueue() { if (isEmpty()) { throw new RuntimeException("队列为空"); } int value = arr[front]; front = (front + 1) % maxSize; return value; } public void showQueue() { if (isEmpty()) { System.out.println("队列为空"); return; } for (int i = front; i < front + size(); i++) { System.out.printf("arr[%d]=%d ", i % maxSize, arr[i % maxSize]); } } public int size() { return (rear + maxSize - front) % maxSize; } public int headQueue() { if (isEmpty()) { throw new RuntimeException("队列为空"); } return arr[front]; } }
以上是关于环形队列的主要内容,如果未能解决你的问题,请参考以下文章