java数据结构之队列

        队列是一个有序列表,可以用数组或者链表实现,遵循先进先出原则,先存入数据先取出,后存入后取出。

        以下是一个数据结构为数组的简单环形队列案例:

/**
 * @author maoyouhua 
 * @version jdk21
 *      数组队列    遵循先进先出的原则
 *      环形队列
 */
public class ArrayQueue {
    private int size;       //队列元素个数
    private int front;      //队列头
    private int rear;       //队列尾
    private final int[] arr;      //数组
    public ArrayQueue(int size) {
        arr = new int[size];
//        front = 0;     //指向队列头
//        rear = 0;      //指向队列尾
    }
    /**
     *      判断队列是否已满
     */
    public boolean isFull(){
        return size == arr.length;
    }
    /**
     *      判断队列是否为空
     */
    public boolean isEmpty(){
        return size == 0;
    }
    /**
     *      入队
     */
    public void addQueue(int n){
        if (isFull()) {
            System.out.println("队列已满,不能添加数据");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % arr.length;
        size++;
    }
    /**
     *      出队
     */
    public int getQueue(){
        if (isEmpty()) {
            throw new RuntimeException("队列为空,不能取出数据");
        }
        int element = arr[front];
        front = (front + 1) % arr.length;
        size--;
        return element;
    }
    /**
     *  遍历
     */
    public void showQueue(){
        if (isEmpty()) {
            throw new RuntimeException("队列为空不能遍历数据");
        }
        for (int i = 0; i < size; i++) {
            System.out.println("队列元素:" + arr[(front + i) % arr.length]);
        }
    }
    /**
     *  展示队列头
     */
    public void headQueue(){
        if (isEmpty()) {
            throw new RuntimeException("队列为空,没有数据");
        }
        System.out.println("队列头的第一个元素是:" + arr[front]);
    }
    /**
     *      返回队列的元素个数
     */
    public int size(){
        return size;
    }

    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(3);
        arrayQueue.addQueue(2);
        arrayQueue.addQueue(3);
        arrayQueue.addQueue(4);
        arrayQueue.showQueue();
        System.out.println("-------------");
        arrayQueue.getQueue();
        arrayQueue.getQueue();
        arrayQueue.addQueue(5);
        arrayQueue.addQueue(6);
        arrayQueue.showQueue();
        arrayQueue.headQueue();
        arrayQueue.showQueue();
        System.out.println("队列元素个数是:" + arrayQueue.size());
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值