java队列的循环数组实现

来源:互联网 发布:无人机与人工智能 编辑:程序博客网 时间:2024/05/18 17:39
package com.yy.queue;/** * 循环数组队列 * @author  * */public class Queue {private int front; //队首指针private int back; //队尾指针private int currentSize; //当前队列大小private Object[] obj; //队列数组/** * 自定义队列初始化长度 * @param length */public Queue(int length){obj = new Object[length];}public Queue(){obj = new Object[10];}/** * 获取当前队列长度 */public int getQueueSize(){//如果 back 指针在 front 指针后面if(front <= back){currentSize = back - front;}else{currentSize = obj.length - front + back;// obj.length - 1 - front + 1 + back;}return currentSize;}/** * 入队操作 */public void enqueue(Object o){//入队时检查队列是否占满了if(currentSize == obj.length){System.out.println("队列已满");return ;}else{//检查 back 指针是否在队列的最后一位if(back == obj.length){//将指针放到第一位back = 0;obj[back++] = o;currentSize++;}else{obj[back++] = o;currentSize++;}}}/** * 出队操作 * 出队操作时有两种情况: 1.指针front不在队尾,此时只需要把指针front++向后挪一次 *     2.指针front在在对尾,此时需要把指针front放到队列数组的第0位 */public void dequeue(){if(currentSize == 0){System.out.println("队列为空");}else{//判断 front 指针是否在队列的最后一位if(front == obj.length - 1){front = 0;currentSize--;}else{front++;currentSize--;}}}/** * 打印循环队列 */public void printQueue(){if(currentSize == 0 && front == back){System.out.println("队列为空");}else if(back <= front){//当循环队列  back 指针在 front 指针前面的时候//先打印front到数组一行结尾的for(int i = front; i < obj.length; i++){System.out.print(obj[i] + " ");}//打印数组从0 开始 到 back指针的位置for(int i = 0; i < back; i++){System.out.print(obj[i] + " ");}}else{//打印从 front 指针到 back 指针位置的队列数据for(int i = front; i < back; i++){System.out.print(obj[i] + " ");}}}/*public static void main(String[] args) {Queue q = new Queue();q.enqueue(1);q.enqueue(2);q.enqueue(3);q.enqueue(4);q.enqueue(5);q.enqueue(6);q.enqueue(7);q.enqueue(8);q.enqueue(9);q.enqueue(10);q.dequeue();q.dequeue();q.enqueue(11);q.enqueue(12);q.dequeue();q.enqueue(11);q.printQueue();System.out.println();System.out.println("currentSize: " + q.currentSize);System.out.println("front指针:" + q.front);System.out.println("back指针:" + q.back);}*/}

原创粉丝点击