数据结构--队列_js+css

学习资源推荐 学习资源推荐


const { log } = console;
function Queue() {

    let schema = [];//用数组保存队列中的元素

    //入队列
    this.enqueue = (item) => (schema.push(item))

    //出队列
    this.dequeue = () => (schema.shift())

    //队首
    this.front = () => (schema[0])

    //队尾
    this.tail = () => (schema[schema.length-1])

    //是否为空队列
    this.isEmpty = () => (schema.length === 0)

    //返回队列中元素个数
    this.size = () => (schema.length)

    //清空队列
    this.clear = () => { schema.length = 0 }

    //打印队列中元素
    this.print = () => { log(schema.toString()); };

}


const queue = new Queue();

log(queue.isEmpty())//true

queue.enqueue(1);//1入队列
queue.enqueue(2);//2入队列

log(queue.front());//队首元素 -> 1

queue.enqueue(3);//3入队列
queue.enqueue(4);//4入队列

log(queue.size());//队列长度 -> 4

log(queue.isEmpty());//false


queue.dequeue();//出队列
queue.dequeue();//出队列

log(queue.size());//队列长度 -> 2
queue.print();//打印队列元素 -> 3,4


module.exports = Queue;