数据结构 队列 数组实现

了解队列

在这里插入图片描述

class ArrayQueue

public class ArrayQueue {
    //用数组来实现队列
    private int[] array;
    //通过maxSize来指定队列的大小
    //通过maxSize我们可以自由实现数组大小的控制
    private int maxSize;
    //队首指针
    private int frontPoint;
    //队尾指针
    private int rearPoint;

    public ArrayQueue(int maxSize) {
        this.maxSize=maxSize;
        array = new int[this.maxSize];
        frontPoint=-1;
        rearPoint=-1;
    }
    /**
     * 判断当前队列是否已满
     */
    public boolean isFull(){
        if(rearPoint==maxSize-1){
            return true;
        }
        return false;
    }
    /**
     * 判断队列是否为空
     */
    public boolean isEmpty(){
        if(rearPoint==frontPoint){
            return true;
        }
        return false;
    }
    /**
     * 添加元素进入队列
     */
    public void add(int n){
        //判断队列是否已经满了
        if(isFull()){
            System.out.println("队列已满");
        }
        rearPoint++;
        array[rearPoint]=n;
//        System.out.println(rearPoint);
    }
    /**
     * 获取队列中的元素并删除元素,出队列
     */
    public int get(){
        if(isEmpty()){
            throw new RuntimeException("空队列");
        }
        frontPoint++;
        return array[frontPoint];
    }
    /**
     * 查看队列中的元素
     */
    public void findQueue(){
        if (isEmpty()){
            throw new RuntimeException("空队列");
        }
        for (int i=frontPoint++;i<array.length;i++){
            System.out.print(array[i]+"\t");
        }
    }
    /**
     * 查看对头的元素,不是出队列
     */
    public int frontQueue(){
        if(isEmpty()){
            throw new RuntimeException("空队列");
        }
        frontPoint++;
        return array[frontPoint];
    }
}

class TestApp

public class TestApp {
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(5);
        arrayQueue.add(1);
        arrayQueue.add(2);
        arrayQueue.add(3);
        arrayQueue.add(4);
        arrayQueue.add(5);
        int i=arrayQueue.get();
        System.out.println(i);
        System.out.println(arrayQueue.isEmpty());
        System.out.println(arrayQueue.isFull());
        System.out.println(arrayQueue.frontQueue());
        arrayQueue.findQueue();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值