java--算法--队列
时间:2021-06-25 16:46:50
收藏:0
阅读:0
- 队列的应用场景:
-
数组模拟队列:
-
package com.model.queue; import java.util.Scanner; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/6/24 20:39 * * 数组模拟队列,并验证 */ public class ArrayQueueDemo01 { public static void main(String[] args) { ArrayQueue queue=new ArrayQueue(3); Scanner scanner = new Scanner(System.in); char key=‘ ‘; 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‘: queue.showQueue(); break; case ‘e‘: scanner.close(); loop=false; break; case ‘a‘: System.out.println("请输入一个选择"); int n=scanner.nextInt(); queue.addQueue(n); break; case ‘g‘: try { int res=queue.getQueue(); System.out.printf("取出的数据是%d\n",res); }catch (Exception e){ System.out.println(e);; }finally { } break; case ‘h‘: try { int head= queue.headQueue(); System.out.printf("取出的数据是%d\n",head); }catch (Exception e){ System.out.println(e); }finally { } break; default: break; } } System.out.println("退出程序"); } } class ArrayQueue{ private int maxSize; //队列的最大长度 private int front; //指向队列头部的前一个 private int rear; //指向队列的尾部 private int[] arr; //数组模拟队列 public ArrayQueue(int maxSize) { this.maxSize = maxSize; arr=new int[maxSize]; } boolean isFull(){ return maxSize-1==rear; } 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("队列为空没有数据"); } 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]; } }
-
评论(0)