面试问题之——如何使用数组实现一个简单队列

分析阶段

我们先来看一下队列和数组都有什么特点

  • 队列
    • 先进先出
    • 在前端进行删除
    • 在后端进行插入
  • 数组
    • 定长
    • 内存地址连续 (与本文无太大关系)
    • 只能存储同一种数据类型

这样看来,用数组实现队列,其实就是想办法使数组变成符合队列存储数据特点的一种实现。

代码演示

package Data;

public class TestQueue<T> {

    //队列头指针
    private int header;

    //队列尾指针
    private int tail;

    //用来表示队列中元素的个数
    private int size;

    //用于实现队列的数组
    private Object[] arr;

    /**
     * 用于初始化队列
     * @param QueueSize 队列容量
     */
    public TestQueue initTestQueue(int QueueSize){
        header=tail=size=0;
        arr = new Object[QueueSize];
        return this;
    }

    /**
     * 将队列元素清空
     */
    public TestQueue clearTestQueue(){
        header=tail=size=0;
        for (int i =0;i<arr.length;i++){
            arr[i]=null;
        }

        return this;
    }

    /**
     * 判断队列中是否为空
     * @return
     */
    public Boolean isEmpty(){
        if (header==tail){
            return true;
        }

        return false;
    }

    /**
     * 入队列
     * @param o 要放入队列的元素
     * @return
     */
    public Boolean addData(Object o) throws Exception {
        if (size>=arr.length){
            throw new Exception("你的队列没有这么长,它最多只能容纳"+arr.length+"个元素");
        }
        if (header==tail){
            header=0;
            arr[header]=o;
            tail=1;
            size++;
            return true;
        } else {
            arr[tail] = o;
            tail=tail+1;
            size++;
            return true;
        }
    }

    /**
     * 获取队头元素
     * @return
     */
    public Object getHeader(){
        return arr[header];
    }


    /**
     *
     * @return
     * @throws Exception
     */
    public Object delData() throws Exception {
        if (header==tail){
            throw new Exception("队列为空无法删除");
        }

        Object t = arr[header];
        arr[header]=null;
        header = header+1;
        size--;
        return t;
    }

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


    public static void main(String[] args) throws Exception {
        TestQueue<Integer> testQueue = new TestQueue<>();

        testQueue.initTestQueue(5);
        testQueue.addData(1);
        testQueue.addData(2);
        testQueue.addData(3);
        testQueue.addData(4);
        testQueue.addData(5);

        testQueue.clearTestQueue();
        System.out.println(testQueue.isEmpty());
        testQueue.addData(5);
        testQueue.addData(6);
        testQueue.addData(7);
        testQueue.addData(8);
        testQueue.addData(9);

        System.out.println(testQueue.getHeader());

        for (int i=0;i<5;i++){
            System.out.println(testQueue.delData());
        }

        System.out.println(testQueue.isEmpty());
    }
}

现在。你已经用数组实现了一个简单队列

猜你喜欢

转载自blog.csdn.net/weixin_45373852/article/details/106254072