数据结构 - 队列

package com.test.testQueue;

public class TestQueue {

    private int start = 0;  //对列头初始位置
    private int end = 0;    //队列尾初始位置
    private int size = 0;   //元素的个数
    private int length = 5; //队列的长度
    private int[] array = new int[length]; //用数组来模拟队列,用下标的数学变化来模拟循环。

    /**
     * 判断队列是否为空
     * @return 空或者不空
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判断队列是否为满状态
     * @return 满或者不满
     */
    public boolean isFull() {
        return (end + 1) % length == start;
    }

    /**
     * 在队列的末尾处入队
     * @param value 入队的元素值
     * @throws Exception 不能在满队列中入队
     */
    public void enqueue(int value) throws Exception {
        if (isFull())
            throw new Exception();
        array[end] = value;
        end = (end + 1) % length;
        size++;
    }

    /**
     * 在队列的头部出列
     * @return 出列的元素值
     * @throws Exception 不能在空队列中出列
     */
    public int dequeue() throws Exception {
        if (isEmpty())
            throw new Exception();
        int value = array[start];
        start = (start + 1) % length;
        size--;
        return value;
    }

    /**
     * 用一个变量i来记录start的值,一共输出j = 0 -> size - 1 个元素值。
     * 为什么不能直接用start?因为在出列中start参与运算,造成值发生改变。
     */
    public void print() {
        for (int i = start, j = 0; j < size; i = (i + 1) % length, j++) {
            System.out.println(array[i] + " " + i);
        }
    }

    public static void main(String[] args) throws Exception {
        TestQueue queue = new TestQueue();
        queue.enqueue(1);
        queue.enqueue(2);
        System.out.println(queue.size);
        queue.print();
        int value = queue.dequeue();
        queue.print();
    }


}





猜你喜欢

转载自blog.csdn.net/qq_34561892/article/details/83757446