単純なキューを実装するために配列を使用する方法に関する質問のインタビュー

分析フェーズ

まず、キューと配列の特性を見てみましょう

  • キュー
    • 先入先出
    • フロントエンドで削除
    • バックエンドに挿入
  • アレイ
    • 固定長
    • メモリアドレスは連続的です(この記事とはあまり関係ありません)
    • 同じデータ型のみを保存できます

このように、配列を使用してキューを実装することは、実際には、配列をキューに格納されているデータの特性に準拠した実装にしようとすることです。

コードデモ

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