1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| package queue;
import java.util.Scanner;
public class ArrayQueueDemo { public static void main1(String args[]) { ArrayQueue arrayQueue = new ArrayQueue(3); char key = ' '; Scanner scanner = new Scanner(System.in); boolean loop = true; while(loop) { System.out.println("s(show):显示队列"); System.out.println("e(exit):退出程序"); System.out.println("a(add):添加数据到队列"); System.out.println("g(get):从队列取出数据"); System.out.println("h(head):显示队列头部数据"); key = scanner.next().charAt(0); switch(key) { case's': arrayQueue.showQueue(); break; case'a': System.out.println("输入一个数字:"); int value = scanner.nextInt(); arrayQueue.addQueue(value); break; case'g': try { int res = arrayQueue.getQueue(); System.out.printf("取出的数据是:%d\n",res); } catch(Exception e) { System.out.println(e.getMessage()); } break; case'h': try { int res = arrayQueue.headQueue(); System.out.printf("队列头的数据是%d",res); } catch(Exception e) { System.out.println(e.getMessage()); } break; case'e': scanner.close(); loop = false; break; default: break; } } System.out.println("程序退出"); } }
class ArrayQueue { private int maxSize; private int front; private int rear; private int[] arr;
public ArrayQueue (int arrMaxSize) { maxSize = arrMaxSize; arr = new int[maxSize]; front = -1; rear = -1; } public boolean isFull() { return rear == maxSize -1; } public boolean isEmpty() { return rear == front; } public void addQueue(int n) { if(isFull()) { System.out.println("队列已满,不能加入数据"); } rear++; arr[rear] = n; } public int getQueue() { if(isEmpty()) { throw new RuntimeException("队列空,不能取出数据"); } front++; return arr[front]; } public void showQueue() { if(isEmpty()) { System.out.println("没有数据!"); return; } for(int i =0;i < arr.length;i++) { System.out.printf("arr[%d]=%d\n", i,arr[i]); } } public int headQueue() { if(isEmpty()) { throw new RuntimeException("队列空"); } return arr[front+1]; } }
|