数组模拟队列(一)

数组模拟队列(一)

数组使用一次不能复用
package com.wmq.atguigu.queue;

import java.util.Scanner;

/**
 * 数组模拟队列
 */
public class ArrayQueueDemo {

    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop){
            char key = scanner.next().charAt(0);
            switch(key){
                case 's':
                queue.showQueue();
                break;
                case 'a':
                    System.out.println("输入一个数");
                    queue.addQueue(scanner.nextInt());
                    break;
                case 'p':
                    try {
                        int i = queue.printQueue();
                        System.out.println("取出的数据为:"+i);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        System.out.println("头数据为:"+queue.headQueue());
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;

                case 'q':
                    scanner.close();
                    loop=false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");
    }

}

class ArrayQueue{
    private int maxSize;
    private int font;
    private int rear;
    private int[] arr;

    public ArrayQueue(int arrMaxSize){
        font = -1;
        rear = -1;
        maxSize = arrMaxSize;
        arr = new int[maxSize];
    }

    //判断队列是否满
    public boolean isFull(){
        return rear == maxSize-1;
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return rear == font;
    }

    //向队列加入数据
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列已满");
            return;
        }else{
            rear++;
            arr[rear] = n;
        }
    }

    //输出队列中的数据
    public int printQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }else{
            font++;
            return arr[font];
        }
    }

    //显示队列中的数据
    public void showQueue(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }else{
            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("队列为空");
        }else{
            return arr[font+1];
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值