当前位置:   article > 正文

Java循环队列_java 循环队列

java 循环队列

目录

一、循环队列

二、设计循环队列


一、循环队列

队列:只能在一端进行插入数据操作,另一端进行删除数据操作的特殊线性表,是一种先进先出的存储结构

插入操作的一端为队尾,删除操作的一端为队头

在线性队列中,一旦队列满了,即使队列的前面有空间,我们也不能插入下一个元素,这时,我们可以使用循环队列,来使用这些空间存储新的值

循环队列: 队头和队尾相连接的队列

二、设计循环队列

我们使用数组来实现循环队列,通过构造器,来创建队列,并设置队列的大小为n

  1. class MyCircularQueue {
  2. private int[] elem;
  3. private int front;
  4. private int rear;
  5. private int size;
  6. public MyCircularQueue(int n) {
  7. elem = new int[n+1];
  8. front = rear = 0;
  9. size = n + 1;
  10. }
  11. }

 在创建队列时,我们预留一个空间,以便判断队列满和计算队列元素个数

判断循环队列是否为空

当队头和队尾指向同一位置时,队列是空的

  1. public boolean isEmpty() {
  2. return front == rear;
  3. }

判断循环队列是否已满

若队尾的下一个位置是队头,那么循环队列已满

 当rear指向最后一个位置时,+1会造成越界,此时我们通过取余(%),让其指向0位置处

  1. public boolean isFull() {
  2. return ((rear+1)%size == front);
  3. }

添加数据

首先判断队列是否已满,若已满,添加失败,返回false,若没有,则在队尾rear位置添加数据,并将rear向后移动

  1. public boolean enQueue(int value) {
  2. //判断队列是否满
  3. if(isFull()){
  4. return false;
  5. }else {
  6. elem[rear] = value;
  7. rear = (rear+1)%size;
  8. return true;
  9. }
  10. }

删除数据

首先判断队列是否为空,若为空,删除失败,返回false,若不为空,则将front向后移动

  1. public boolean deQueue() {
  2. //队列是否为空
  3. if(isEmpty()){
  4. return false;
  5. }else {
  6. front = (front + 1) % size;
  7. return true;
  8. }
  9. }

获取队头元素

首先判断队列是否为空,若为空,队列中无元素,抛出异常,若不为空,返回队头元素,并将front向后移动

  1. public int getFront() {
  2. if(isEmpty()){
  3. throw new RuntimeException("队列为空,无元素!");
  4. }else {
  5. int val = elem[front];
  6. front = (front + 1) % size;
  7. return val;
  8. }
  9. }

计算队列中元素个数

  1. public int size(){
  2. return (rear + size - front) % size;
  3. }

完整代码

  1. class MyCircularQueue {
  2. private int[] elem;
  3. private int front;
  4. private int rear;
  5. private int size;
  6. public MyCircularQueue(int n) {
  7. elem = new int[n+1];
  8. front = rear = 0;
  9. size = n + 1;
  10. }
  11. public boolean isEmpty() {
  12. return front == rear;
  13. }
  14. public boolean isFull() {
  15. return ((rear+1)%size == front);
  16. }
  17. public boolean enQueue(int value) {
  18. //判断队列是否满
  19. if(isFull()){
  20. return false;
  21. }else {
  22. elem[rear] = value;
  23. rear = (rear+1)%size;
  24. return true;
  25. }
  26. }
  27. public boolean deQueue() {
  28. //队列是否为空
  29. if(isEmpty()){
  30. return false;
  31. }else {
  32. front = (front + 1) % size;
  33. return true;
  34. }
  35. }
  36. public int getFront() {
  37. if(isEmpty()){
  38. throw new RuntimeException("队列为空,无元素!");
  39. }else {
  40. int val = elem[front];
  41. front = (front + 1) % size;
  42. return val;
  43. }
  44. }
  45. public int size(){
  46. return (rear + size - front) % size;
  47. }
  48. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/884836
推荐阅读
相关标签
  

闽ICP备14008679号