环形队列
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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| package com.xiaohu.suanfa.queue;
import java.util.Scanner;
public class CircularQueue { class ArrayQueue { private int maxSize; private int head; private int tail; private int[] arr;
public ArrayQueue(int maxsize) { this.maxSize = maxsize + 1; arr = new int[maxsize]; head = 0; tail = 0; }
private boolean isEmpty() { return head == tail; }
private boolean isFull() { return (tail + 1) % maxSize == head; }
private void add(int num) { if (isFull()) { throw new RuntimeException("队列已满,无法添加元素"); } arr[tail] = num; tail = (tail + 1) % maxSize; System.out.println("添加成功"); }
private int get() { if (isEmpty()) { throw new RuntimeException("队列为空,无法获得元素"); } int temp = arr[head]; head = (head + 1) % maxSize; return temp; }
public void showElem() { if (isEmpty()) { System.out.println("队列为空~~"); } for (int i = head; i < ((tail + maxSize - head) % maxSize)+ head; i++) {
System.out.printf("%d\t", arr[i % maxSize]); System.out.println(""); } }
private int getHead() { if (isEmpty()) { System.out.println("队列为空~~"); } return arr[head]; } }
public static void main(String[] args) { ArrayQueue q = new CircularQueue().new ArrayQueue(4); char c; Scanner scanner = new Scanner(System.in); boolean loop = true; while (loop) { System.out.println("s: 显示队列"); System.out.println("e: 退出应用"); System.out.println("a: 元素入队尾"); System.out.println("g: 从队头取出元素"); System.out.println("h: 查看队头元素"); System.out.println("请输入你的操作"); c = scanner.next().charAt(0); switch (c) { case 's': q.showElem();
break; case 'a': try { System.out.println("请输入一个数"); int v = scanner.nextInt();
q.add(v); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'g': try { int res = q.get(); System.out.println("取出了 " + res); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'h': try { int res = q.getHead(); System.out.println("队头元素 " + res); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'e': loop = false; System.out.println("程序退出~"); break; default: System.out.println("指令非法,请重新输入正确的指令~"); } } }
}
|