JS 模拟 循环队列

 Loop Array 代码(基于JS原生数组)

/**
 * 循环队列
 */
var ALoopQueue = (function () {
    /**
     * @type {Array}
     */
    let arr;
    /**
     * 头节点
     * @type {number}
     */
    let frontIdx;
    /**
     * 尾节点
     * @type {number}
     */
    let tailIdx;
    /**
     * 元素数量
     * @type {number}
     */
    let size;

    /**
     * 
     * @param {number} new_capacity 
     */
    const resize = (new_capacity) => {
        const data = new Array(new_capacity + 1);
        const len = arr.length;
        for (let i = 0; i < size; i++) {
            data[i] = arr[(i + frontIdx) % len];
        }
        arr = data;
        frontIdx = 0;
        tailIdx = size;
    };

    /**
     * @class
     */
    class _ALoopQueue {
        /**
         * 构造器
         * @constructor
         * @param {number} capacity 
         */
        constructor(capacity = 10) {
            arr = new Array(capacity + 1);
            frontIdx = 0;
            tailIdx = 0;
            size = 0;
        }

        /**
         * 获取当前的数据容量
         * @returns 
         */
        get_capacity() {
            return arr.length - 1;
        }

        /**
         * 获取元素个数
         * @returns 
         */
        get_size() {
            return size;
        }

        /**
         * 当前容器是否为空
         * @returns 
         */
        is_empty() {
            return frontIdx === tailIdx;
        }

        /**
         * 入队操作
         * @param el 
         */
        enqueue(el) {
            // % 运算优先级高于 +
            if ((tailIdx + 1) % arr.length === frontIdx) {
                resize(this.get_capacity() * 2);
            }
            arr[tailIdx] = el;
            tailIdx = (tailIdx + 1) % arr.length;
            size++;
        }

        /**
         * 出队操作
         * @returns 
         */
        dequeue() {
            if (this.is_empty()) {
                throw new Error('队列为空,无法执行出队操作!');
            }
            const tar = arr[frontIdx];
            arr[frontIdx] = void 0;
            frontIdx = (frontIdx + 1) % arr.length;
            size--;
            const cap = this.get_capacity();
            if (size === Math.floor(cap / 4) && Math.floor(cap / 2) !== 0) {
                resize(Math.floor(cap / 2));
            }
            return tar;
        }

        /**
         * 获取头部元素
         * @returns 
         */
        get_front() {
            if (this.is_empty()) {
                throw new Error('队列为空!');
            }
            return arr[frontIdx];
        }

        /**
         * 获取数据的字符串描述
         * @returns 
         */
        to_string() {
            let str = 'Loop Queue: size=' + size + ', capacity=' + this.get_capacity() + '; front [';
            if (size > 0) {
                str += arr[frontIdx];
            }
            if (frontIdx < tailIdx) {
                for (let i = frontIdx + 1; i !== tailIdx; i = (i + 1) % arr.length) {
                    str += (',' + arr[i]);
                }
            }
            str += '] tail';
            return str;
        }
    }

    return _ALoopQueue;
})();

 

Java版笔记

public interface Queue<E> {
    int getSize();
    boolean isEmpty();
    void enqueue(E e);
    E dequeue();
    E getFront();
}

public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int front;
    private int tail;
    private int size;

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    public int getCapacity() {
        return data.length;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(E e) {
        if (size == getCapacity()) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("队列已为空!");
        }
        E tar = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return tar;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("队列已为空!");
        }
        return data[front];
    }

    private void resize(int newCapacity) {
        E[] newData = (E[])new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    public String toString() {
        StringBuffer res = new StringBuffer();
        res.append("front: [");
        for (int i = 0; i < size; i++) {
            res.append(data[(front + i) % data.length]);
            if ((i + front + 1) % data.length != tail) {
                res.append(", ");
            }
        }
        res.append("] tail.");
        return res.toString();
    }

    public static void main(String[] args) {
        LoopQueue<Integer> q = new LoopQueue<>();
        for (int i = 0; i < 10; i++) {
            q.enqueue(i);
            System.out.println(q);
            if (i % 3 == 2) {
                q.dequeue();
                System.out.println(q);
            }
        }
    }
}

 

posted @ 2023-06-27 15:02  樊顺  阅读(20)  评论(0编辑  收藏  举报