循环队列注意点及实现
队尾插入元素(rear),队头元素出队(front)
1.循环队列内元素个数等于数组或者链表元素长度减一时,即可认为循环链表已经装满,否则队列满和队列为空的判断条件相同
即 (arr.length - 1 == size) => 队列满 ,或者 (list.getLength() - 1 == size) => 队列满
2.队满判断条件:
(rear+1)%arr.length == front
3.队列为空的判断条件:
rear == front
4.元素出队和元素入队之后索引的变化都是(指针+1)%arr.length
(队头)元素出队:front = (front+1)%arr.length
(队尾)元素入队:rear = (rear+1)%arr.length
public class Circular_queue { private int[] arr;//采用数组实现循环队列 private int front;//队头指针 private int rear;//队尾指针 public Circular_queue() { } /** * @param length 队列空间大小 */ public Circular_queue(int length){ arr = new int[length]; } //插入元素 public void insert(int value) throws Exception { //队列满了 if((rear+1)%arr.length==front){ throw new Exception("队列满了。。。"); } arr[rear] = value; rear = (rear+1)%arr.length; } //元素出队 public int pop() throws Exception { if(rear==front){ throw new Exception("队列内为空。。"); } int result = arr[front]; front = (front+1)%arr.length; return result; } //展示所有元素 public void showAll() throws Exception { int _rear = rear; int _front = front; System.out.println("开始打印数据~~~~~~"); while (_rear!=_front){ System.out.println(arr[_front]); _front = (_front+1)%arr.length; } System.out.println("数据打印完毕~~~~~~"); } }