用数组实现 最简 非环形队列

可以比较直观地理解队列的模型~~


 import java.util.Scanner;
 
 /**
  * 使用数组完成队列功能
  */
 public class ArrayQDemo {
     public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         System.out.println("输入数字,创建一个队列");
         ArrayQu arrayQu = new ArrayQu(sc.nextInt());
 
         while (true){
             System.out.println("*******************");
             System.out.println("1: 展示队列");
             System.out.println("2: 添加队列信息");
             System.out.println("3: 取值");
             System.out.println("9: 退出");
             System.out.println("*******************");
             switch (sc.nextInt()){
                 case 1:{
                     arrayQu.showQ();
                     break;
                }
                 case 2:{
                     System.out.println("请输入一个数");
                     arrayQu.add(sc.nextInt());
                     break;
                }
                 case 3:{
                     arrayQu.get();
                     arrayQu.showQ();
                     break;
                }
                 case 9:{
                     int i = 1;
                     System.exit(i);
                     break;
                }
                 default:{
                     System.out.println("请输入正确的字符");
                     break;
                }
            }
        }
 
    }
 }
 
 
 class ArrayQu {
     private int maxSize;
     private int headNode;
     private int bottomNode;
     private int[] arr;
 
     public ArrayQu(int arrMaxSize) {
         maxSize = arrMaxSize;
         headNode = 0;
         bottomNode = 0;
         arr = new int[maxSize];
    }
 
     public boolean isEmpty() {
         return headNode == bottomNode;
    }
 
     public boolean isFull() {
         return headNode == maxSize;
    }
 
     public void add(int a) {
         if (!isFull()) {
             arr[headNode] = a;
             headNode++;
             System.out.println("加入成功");
        } else {
             System.out.println("加入失败");
        }
    }
 
     public int get() {
         int temp = 0;
         if (isEmpty()) {
             throw new RuntimeException("队列为空,不可取值");
        } else {
            temp = arr[0];
            headNode--;
             for (int i = 0; i < headNode; i++) {
                 arr[i] = arr[i + 1];
            }
 
             return temp;
 
        }
    }
     public void showQ(){
         if (!isEmpty()){
             for (int i = headNode-1; i >= 0; i--) {
                 System.out.print("| ");
                 System.out.printf("___"+arr[i]+"___");
                 System.out.println(" |");
            }
        }else {
             System.out.println("队列为空,不可展示");
        }
    }
 }

 

posted @ 2020-02-27 10:23  白码王子与七个技术栈  阅读(247)  评论(0编辑  收藏  举报