线性数据结构-队列

队列(Queue)是一种先进先出(First In First Out, FIFO)的数据结构,它按照元素进入的顺序来处理元素。队列的基本操作包括:

  • enqueue:在队列的末尾添加一个元素。
  • dequeue:移除队列的第一个元素,并返回被移除的元素。
  • front 或 peek:返回队列的第一个元素,但不移除它。
  • isEmpty:检查队列是否为空。
  • size:返回队列中元素的数量。

数组实现队列

  • 内存连续性:数组在内存中是连续分配的,这有助于利用现代处理器的缓存机制,提高访问速度。
  • 动态扩容:数组需要预先定义大小或动态扩容。动态扩容涉及到创建新数组并复制旧数组元素的操作,这个操作的时间复杂度为O(n)。
  • 插入和删除操作:在队列末尾插入元素(enqueue)的时间复杂度为O(1),但在队列开头删除元素(dequeue)时,由于需要移动所有后续元素,时间复杂度也为O(n)。不过,如果只在数组末尾进行操作,这个复杂度可以降低到O(1)。
javascript 复制代码
class Queue {
    contructor(){
        this._queue = [];
    }

    isEmty() {
        return this._queue.length === 0;
    }

    enqueue(value) {
        this._queue.push(value);
    }

    dequeue() {
        if (this.isEmty()) {
            return undefined;
        }
        return this._queue.shift();
    }
    
    size() {
        return this._queue.length;
    }

    peek() {
        if (this.isEmty()) {
            return undefined;
        }
        return this._queue[0];
    }
}

链表实现队列

  • 内存分配:链表节点在内存中可以分散分配,不需要连续的内存空间。
  • 动态大小:链表可以根据需要动态地分配节点,不需要担心扩容问题。
  • 插入和删除操作:在链表队列的末尾插入元素(enqueue)和从头部删除元素(dequeue)的时间复杂度都为O(1),因为只需要改变指针的指向。
  • 额外开销:链表操作涉及到额外的指针操作,可能会有一些性能开销,尤其是在js中,对象和指针的处理通常比原始数据类型慢。
javascript 复制代码
class Node {
    constructor(value){
        this.value = value;
        this.next  = null;
    }
}


class Queue {
    contructor(){
        this._front = null
        this._rear = null
        this._size = 0
    }

    isEmty() {
        return this._size === 0;
    }

    size() {
        return this._size;
    }

    dequeue() {
        if (this.isEmty()) {
            return undefined;
        }
        this._size--
        const removeNode = this._front
        this._front = this._front.next
        if (this.isEmty()) {
            this._rear = null
        }
        return removeNode.value;
    }
    
    enqueue(value) {
        const newNode = new Node(value)
        if (this.isEmty()) {
            this._front = newNode
            this._rear = newNode
        } else {
            this._rear.next = newNode
            this._rear = newNode
        }
        this._size++
    }
    peek() {
        if (this.isEmty()) {
            return undefined;
        }
        return  this._front.value;
    }
}
相关推荐
TTGGGFF26 分钟前
Supertonic 部署与使用全流程保姆级指南(附已部署镜像)
开发语言·python
黎雁·泠崖27 分钟前
栈与队列实战通关:3道经典OJ题深度解析
c语言·数据结构·leetcode
木木木一30 分钟前
Rust学习记录--C7 Package, Crate, Module
开发语言·学习·rust
love530love30 分钟前
升级到 ComfyUI Desktop v0.7.0 版本后启动日志报 KeyError: ‘tensorrt‘ 错误解决方案
开发语言·windows·python·pycharm·virtualenv·comfyui·comfyui desktop
Evand J1 小时前
【MATLAB例程】【空地协同】UAV辅助的UGV协同定位,无人机辅助地面无人车定位,带滤波,附MATLAB代码下载链接
开发语言·matlab·无人机·无人车·uav·协同定位·ugv
火星牛2 小时前
AI IDE试用(一)
javascript·ide
chao1898442 小时前
基于MATLAB实现多变量高斯过程回归(GPR)
开发语言·matlab·回归
jump_jump4 小时前
基于 Squoosh WASM 的浏览器端图片转换库
前端·javascript·性能优化
ytttr8737 小时前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab
天远Date Lab7 小时前
Python实战:对接天远数据手机号码归属地API,实现精准用户分群与本地化运营
大数据·开发语言·python