首页 > 其他 > 详细

2.队列

时间:2021-04-06 12:45:32      阅读:10      评论:0      收藏:0      [点我收藏+]

队列

先进先出

1 数组模拟环形队列

public class ArrayQueue {

    //定义队列
    private int maxSize;
    private int front;//指向第一个元素
    private int rear;//指向最后一个元素的后一个位置
    private int[] arr;

    //构造器
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
    }

    //判断是否为满,
    public boolean isFull() {
        return (this.rear + 1) % this.maxSize == this.front;
    }

    //判断是否为空
    public boolean isEmpty() {
        return this.rear == this.front;
    }

    //入队
    public void pushQueue(int n) {
        //判满
        if (this.isFull()) {
            System.out.println("Full Queue!");
            return;
        }
        //从尾部入队
        this.arr[this.rear] = n;
        this.rear = (this.rear + 1) % this.maxSize;
    }

    //出队
    public int popQueue() {
        //判空
        if (isEmpty()) {
            throw new RuntimeException("Empty Queue!");
        }
        int temp = this.arr[this.front];
        this.front = (this.front + 1) % this.maxSize;
        return temp;
    }

    //有效数据个数
    public int size() {
        return (this.rear + this.maxSize - this.front) % maxSize;
    }

    //显示
    public void showQueue() {
        if (this.isEmpty()) {
            System.out.println("Empty Queue!");
            return;
        }
        for (int i = this.front; i < this.front + this.size(); i++) {
            System.out.printf("arr[%d] = %d\n", i % this.maxSize, this.arr[i % this.maxSize]);
        }
    }

    //显示队头
    public int getHead() {
        if (isEmpty()) {
            throw new RuntimeException("Empty Queue!");
        }
        return this.arr[this.front];
    }

}

2.队列

原文:https://www.cnblogs.com/fremontxutheultimate/p/14585472.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!