//获取队列的数据a public int getQueue(){ //先判断数据是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,不能取数据~~"); } int num = arr[front]; front++; return num; }
//显示队列的所有数据 public void showQueue(){ //先判断数据是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,不能取数据~~"); } 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("数据为空,不能取数据~~"); } int b = arr[front]; return b; }
//获取尾部的数据 public int rearQueue(){ //先判断数据是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,不能取数据~~"); } int a = arr[rear-1]; return a; }
注:这种方法实现的队列不能复用,只能使用一次,下面使用循环数组来实现。
public static void main(String[] args) { //开始操作环形数据 AnnularQueue queue = new AnnularQueue(4); Scanner scanner = new Scanner(System.in); boolean loop = true; while(loop){ System.out.println("请输入对应的字母开始操作程序:"); System.out.println("a: 添加元素"); System.out.println("b: 取出元素"); System.out.println("c: 取出队列的头部元素"); System.out.println("d: 取出队列的尾部元素"); System.out.println("e: 遍历所有的元素"); System.out.println("f: 退出程序"); char ch = scanner.next().charAt(0); switch (ch) { case 'a': System.out.println("请输入一个数据:"); int num = scanner.nextInt(); queue.addQueue(num); break; case 'b': try { int b = queue.getQueue(); System.out.println(b); } catch (Exception e) { System.out.println(e.getMessage()); }
break; case 'c': try { int c = queue.headQueue(); System.out.println(c); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'd': try { int d = queue.tailQueue(); System.out.println(d); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'e': try { queue.showQueue(); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'f': scanner.close(); loop = false; break; default: break; } } } }
class AnnularQueue{ private int maxSize;//队列的容量 private int rear;//队列尾 private int front;//队列头 private int[] array;//存放队列的数据
/** * 增加队列的构造方法 */ public AnnularQueue(int maxSize){ this.maxSize = maxSize; array = new int[maxSize]; rear = 0;//队列头默认从0开始, front = 0; }
/** * 获取元素 */ public int getQueue(){ //判断队列是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,无法取数据~~"); } int num = array[front]; //对front自增取模操作 front = (front + 1) % maxSize; return num; }
/** * 遍历元素 */ public void showQueue(){ //判断队列是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,无法取数据~~"); } for (int i = front; i < front + getSize(); i++) { System.out.printf("arr[%d] = %d\n",i % maxSize ,array[i % maxSize]); } }
/** * 查询有效的元素 */ public int getSize(){
return (rear + maxSize - front) % maxSize; }
/** * 取出头部元素 */ public int headQueue(){ //判断队列是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,无法取数据~~"); } return array[front]; }
/** * 取出尾部元素 */ public int tailQueue(){ //判断队列是否为空 if(isEmpty()){ throw new RuntimeException("数据为空,无法取数据~~"); } if(rear==0){ rear = 4; } return array[rear-1]; }