数据结构与算法(java)—— 队列


https://blog.csdn.net/weixin_44187730/article/details/96141225

队列的实现

队列为先进先出,队列可以由数组实现,也可以由链表实现。

数组实现单向队列

package DataStructure;

public class ArrayQueueDemo {
    //测试队列
    public static void main(String[] args) {

        ArrayQueue arrayQueue = new ArrayQueue(20);
        arrayQueue.add(2);
        arrayQueue.add(24);
        arrayQueue.add(23);
        arrayQueue.add(22);
        arrayQueue.add(21);
        arrayQueue.showQueue();
        System.out.println(arrayQueue.removeElement());
        System.out.println(arrayQueue.removeElement());
        arrayQueue.showQueue();
        
    }


}

class ArrayQueue {
    private int[] array;//数组存储数据
    private int maxSize;//队列容量
    private int front; //头指针,取出时用
    private int rear;//尾指针,添加时用


    /**
     * 构造方法,传入队列的容量
     *
     * @param maxSize
     */
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        front = -1;//指向头部前一个位置
        rear = -1;//指向尾部位置
        array = new int[maxSize];

    }

    /**
     * 判断队列是否满了
     * 如果尾部位置指向maxsize-1就满了
     *
     * @return
     */
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    /**
     * 判断队列是否为空
     * 如果尾部指针和头部指针相同,则为空
     *
     * @return
     */
    public boolean isEmpty() {
        return front == rear;
    }

    /**
     * 向队列中添加元素
     * 1。判断是否满
     * 2。尾部指针往后移动
     * 3。添加元素到数组
     *
     * @param num
     */
    public void add(int num) {
        if (isFull()) {
            System.out.println("Queue is full !");
            return;
        }
        rear++;
        array[rear] = num;
    }

    /**
     * 从队列中取出元素
     * 1。先判断是否为空,为空则抛出异常
     * 2。头部指针后移
     * 3。取出头部指针的元素
     */
    public int removeElement() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is empty !!!");
        }
        front++;
        return array[front];
    }

    /**
     * 打印队列
     * 1。判断为空则无数据
     * 2。for循环打印数组中的数据
     */
    public void showQueue(){
        if (isEmpty()){
            System.out.println("Queue is Empty, no data for printing...");
            return;
        }

        for (int i = front+1; i <= rear; i++) {
            System.out.print(array[i]+",");
        }

        System.out.println();
    }

}

该队列只能使用一次,因为在使用过程移动指针后,指针后移就不能再使用该队列了。

发布了103 篇原创文章 · 获赞 94 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/chongbin007/article/details/102594715