Java数据结构——队列
介绍
1.队列是一个有序列表,可以用数组或链表实现
2.遵循先入先出的原则,即:现存入队列的数据,要先取出,后存入的数据,后取出
3.示意图:
数组模拟队列
队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如上图,其中maxSize是该队列的最大容量
因为队列的输出、输入是分别从前后端来处理,因此需要两个变量front及rear分别记录队列前后端的下标,front会随着数据的输出而改变,而rear则是随着数据输入而改变
代码实现:
1 package com.taru.queue; 2 3 import java.util.Scanner; 4 5 public class ArrayQueueDemo { 6 public static void main(String[] args) { 7 ArrayQueue queue = new ArrayQueue(5); 8 char key = ' ';//接收用户输入 9 Scanner scanner = new Scanner(System.in); 10 boolean loop = true; 11 while (loop){ 12 System.out.println("s(show):显示队列"); 13 System.out.println("e(exit):退出程序"); 14 System.out.println("a(add):添加数据到队列"); 15 System.out.println("g(get):从队列取出数据"); 16 System.out.println("h(head):显示队列头部"); 17 key = scanner.next().charAt(0); 18 switch (key){ 19 case 's': 20 queue.showQueue(); 21 break; 22 case 'a': 23 System.out.println("输入一个数:"); 24 int value = scanner.nextInt(); 25 queue.addQueue(value); 26 break; 27 case 'g': 28 try { 29 int res = queue.getQueue(); 30 System.out.println("取出的数据:" +res); 31 }catch (Exception e){ 32 e.printStackTrace(); 33 } 34 break; 35 case 'h': 36 try { 37 int head = queue.headQueue(); 38 System.out.println("取出的头部数据:"+head); 39 }catch (Exception e){ 40 e.printStackTrace(); 41 } 42 break; 43 case 'e': 44 scanner.close(); 45 loop = false; 46 break; 47 default: 48 break; 49 } 50 } 51 System.out.println("程序已退出----"); 52 } 53 } 54 class ArrayQueue{ 55 private int maxSize;//表示数组最大容量 56 private int front;//表示队列头部 57 private int rear;//表示队列尾部 58 private int[] arr;//存放数据,模拟队列 59 public ArrayQueue(int arrMaxSize){ 60 maxSize = arrMaxSize; 61 arr = new int[arrMaxSize]; 62 front=-1;//指向队列头部 63 rear=-1;//指向队列尾部 64 } 65 //判断是否满 66 public boolean isFull(){ 67 return rear == maxSize -1; 68 } 69 //判断是否为空 70 public boolean isEmpty(){ 71 return front == rear; 72 } 73 //加入队列数据 74 public void addQueue(int n){ 75 if (isFull()){ 76 System.out.println("队列已满,无法加入----"); 77 return; 78 } 79 rear++; 80 arr[rear] = n; 81 } 82 //取出队列数据 83 public int getQueue(){ 84 if (isEmpty()){ 85 throw new RuntimeException("队列为空,无法取出数据"); 86 } 87 front++; 88 return arr[front]; 89 } 90 //查看所有队列数据 91 public void showQueue(){ 92 int j = rear; 93 if (isEmpty()){ 94 System.out.println("队列为空----"); 95 return; 96 } 97 for (int i = front+1 ; i<=j;i++){ 98 System.out.printf("arr[%d]=%d\t",i,arr[i]); 99 } 100 System.out.println(); 101 } 102 //查看队列头部数据 103 public int headQueue(){ 104 if (isEmpty()){ 105 throw new RuntimeException("队列为空,无法显示队列头部数据-----"); 106 } 107 return arr[front+1]; 108 } 109 }
问题分析及优化
1.目前数组仅可使用一次,没有达到复用的效果
2.可将改进成一个环形数组,使之成为环形队列