Implemented using a queue array

We first need to define what is a queue

Queue (Queue), a linear data structure is stored. It has the following characteristics:

  • In accordance with the data queue "先进先出(FIFO, First-In-First-Out)"way out of the queue.
  • In queue only "队首"a delete operation, and in the "队尾"insertion operation.
  • The queue typically includes two operations: 入队列and 出队列.

Ado, one can simply implemented using an array of digital storage elements in the queue, the code is:

/**
 * 实现一个能简单存储数字元素的队列
 */
public class ArrayQueue {
    /**
     * 声明一个数组
     */
    private int[] array;
    /**
     * 声明队中元素的数量
     */
    private int count;

    /**
     * 初始化队列使用,传入一个初始长度
     *
     * @param size
     */
    public ArrayQueue(int size) {
        array = new int[size];
        count = 0;
    }

    /**
     * 入队列,向队列的尾部添加元素,同时队列的长度加1
     *
     * @param val
     */
    public void push(int val) {
        array[count++] = val;
    }

    /**
     * 返回队首的元素
     *
     * @return
     */
    public int front() {
        return array[0];
    }

    /**
     * 返回队首元素的同时从队列中移除该元素
     *
     * @return
     */
    public int pop() {
        int ret = array[0];
        count--;
        for (int i = 1; i <= count; i++) {
            array[i - 1] = array[i];
        }
        return ret;
    }

    /**
     * 返回队列的长度
     *
     * @return
     */
    public int size() {
        return count;
    }

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

Guess you like

Origin blog.csdn.net/weixin_44290425/article/details/88561893