使用循环数组来实现
1 package QueueImpl_Array; 2 3 import java.util.Random; 4 5 /** 6 * 实现步骤: 7 * 队列特点;先进先出,所以可以让front指针指向移出的数,end指针指向插入的数 8 * maxSize:数组长度 9 * 头指针:front 10 * 尾指针:end 11 * 队列长度:lenth 12 * 13 */ 14 15 public class demo_Array { 16 public static int length = 0; 17 public static int maxSize = 20; 18 public static int front = 0; 19 public static int end = 0; 20 public static int[] queueArray = new int[maxSize]; 21 22 23 public static void main(String[] args) { 24 25 // Random r = new Random(); 26 27 System.out.println(demo_Array.pick()); 28 29 for (int i = 0; i < 15; i++) { 30 demo_Array.insert(i); 31 32 } 33 34 for (int i = 0; i < queueArray.length; i++) { 35 System.out.println("队列中"+"第"+i+"个值为:"+queueArray[i]); 36 37 } 38 for (int i = 0; i < 10; i++) { 39 demo_Array.remove(); 40 41 } 42 43 for (int i = 20; i < 30; i++) { 44 demo_Array.insert(i); 45 46 } 47 System.out.println(demo_Array.pick()); 48 49 50 51 52 53 } 54 55 56 public static boolean isFull() { 57 if(length == 0) 58 return true; 59 return false; 60 } 61 62 public static boolean isEmpty(){ 63 if(length == maxSize) 64 return true; 65 return false; 66 } 67 68 public static void insert(int insertData){ 69 if(length == maxSize) 70 System.out.println("队列已满,无法插入"); 71 else if(end == maxSize - 1) { 72 end =0; 73 queueArray[end] = insertData; 74 } 75 else { 76 queueArray[end++] = insertData; 77 length++; 78 } 79 80 } 81 82 public static int remove(){ 83 if(length == 0) 84 System.out.println("队列已空,无法消除"); 85 else if(front == maxSize - 1){ 86 front = 0; 87 length--; 88 return queueArray[front]; 89 90 } 91 length--; 92 93 return queueArray[front++]; 94 95 } 96 97 public static int pick(){ 98 return queueArray[front]; 99 } 100 101 102 }