TypeScript 队列实战:从零实现简单、循环、双端、优先队列,附完整测试代码
TypeScript 队列实战从零实现简单、循环、双端、优先队列附完整测试代码引言队列Queue是计算机科学中最基础也最实用的数据结构之一遵循FIFO先进先出原则。在实际开发中从任务调度到消息中间件从广度优先搜索到滑动窗口算法队列无处不在。本文将通过 TypeScript 从零实现四种经典队列并附带完整的单元测试代码帮助你深入理解队列的底层原理。## 1. 简单队列Simple Queue简单队列是最基础的实现支持enqueue入队和dequeue出队操作。我们使用数组作为底层存储。typescript// 简单队列接口interface IQueueT { enqueue(element: T): void; dequeue(): T | undefined; peek(): T | undefined; isEmpty(): boolean; size(): number;}// 简单队列实现class SimpleQueueT implements IQueueT { private items: T[] []; // 入队将元素添加到队列尾部 enqueue(element: T): void { this.items.push(element); } // 出队移除并返回队列头部元素 dequeue(): T | undefined { if (this.isEmpty()) { return undefined; } return this.items.shift(); } // 查看队列头部元素不移除 peek(): T | undefined { if (this.isEmpty()) { return undefined; } return this.items[0]; } // 判断队列是否为空 isEmpty(): boolean { return this.items.length 0; } // 获取队列大小 size(): number { return this.items.length; }}// 测试代码const simpleQueue new SimpleQueuenumber();simpleQueue.enqueue(10);simpleQueue.enqueue(20);simpleQueue.enqueue(30);console.log(简单队列测试:);console.log(出队:, simpleQueue.dequeue()); // 10console.log(队列大小:, simpleQueue.size()); // 2console.log(队列是否为空:, simpleQueue.isEmpty()); // false性能分析简单队列的dequeue操作使用shift()时间复杂度为 O(n)因为数组需要移动后续元素。这在数据量较大时效率较低。## 2. 循环队列Circular Queue循环队列通过复用数组空间解决简单队列的 O(n) 问题使用头尾指针实现 O(1) 的入队和出队。typescript// 循环队列实现class CircularQueueT { private items: (T | undefined)[]; // 底层数组允许 undefined 占位 private head: number 0; // 头指针 private tail: number 0; // 尾指针 private count: number 0; // 当前元素个数 private capacity: number; // 队列容量 constructor(capacity: number) { this.capacity capacity; this.items new Array(capacity).fill(undefined); } // 入队在尾部添加元素 enqueue(element: T): boolean { if (this.isFull()) { console.warn(队列已满无法入队); return false; } this.items[this.tail] element; // 在 tail 位置放入元素 this.tail (this.tail 1) % this.capacity; // 循环移动 tail this.count; return true; } // 出队移除并返回头部元素 dequeue(): T | undefined { if (this.isEmpty()) { return undefined; } const element this.items[this.head]; // 获取头部元素 this.items[this.head] undefined; // 清理空间 this.head (this.head 1) % this.capacity; // 循环移动 head this.count--; return element; } // 判断队列是否为空 isEmpty(): boolean { return this.count 0; } // 判断队列是否已满 isFull(): boolean { return this.count this.capacity; } // 查看头部元素 peek(): T | undefined { return this.items[this.head]; } // 获取当前元素个数 size(): number { return this.count; }}// 测试循环队列const circularQueue new CircularQueuenumber(3);circularQueue.enqueue(1);circularQueue.enqueue(2);circularQueue.enqueue(3);console.log(\n循环队列测试:);console.log(入队 4队列已满:, circularQueue.enqueue(4)); // falseconsole.log(出队:, circularQueue.dequeue()); // 1console.log(再次入队 4:, circularQueue.enqueue(4)); // trueconsole.log(队列状态:);while (!circularQueue.isEmpty()) { console.log(出队:, circularQueue.dequeue()); // 2, 3, 4}核心优势所有操作均为 O(1)适合固定容量的场景如操作系统中的任务队列。## 3. 双端队列Deque双端队列允许在两端进行插入和删除结合了栈和队列的特性。typescript// 双端队列实现class DequeT { private items: T[] []; private front: number 0; // 前端指针 private back: number 0; // 后端指针 // 从前端添加元素 addFront(element: T): void { // 如果队列为空直接添加到后端 if (this.isEmpty()) { this.addBack(element); return; } // 否则在 front 之前插入需要扩展数组 this.front--; // 如果 front 变为负数需要调整数组 if (this.front 0) { this.items.unshift(element); // 在数组头部插入 this.front 0; this.back; } else { this.items[this.front] element; } } // 从后端添加元素 addBack(element: T): void { this.items[this.back] element; this.back; } // 从前端移除元素 removeFront(): T | undefined { if (this.isEmpty()) return undefined; const element this.items[this.front]; this.items[this.front] undefined as any; this.front; if (this.front this.back) { this.front 0; this.back 0; } return element; } // 从后端移除元素 removeBack(): T | undefined { if (this.isEmpty()) return undefined; this.back--; const element this.items[this.back]; this.items[this.back] undefined as any; if (this.front this.back) { this.front 0; this.back 0; } return element; } // 查看前端元素 peekFront(): T | undefined { return this.items[this.front]; } // 查看后端元素 peekBack(): T | undefined { return this.items[this.back - 1]; } isEmpty(): boolean { return this.front this.back; } size(): number { return this.back - this.front; }}// 测试双端队列const deque new Dequenumber();deque.addBack(1);deque.addBack(2);deque.addFront(0);console.log(\n双端队列测试:);console.log(前端元素:, deque.peekFront()); // 0console.log(后端元素:, deque.peekBack()); // 2console.log(移除前端:, deque.removeFront()); // 0console.log(移除后端:, deque.removeBack()); // 2console.log(队列大小:, deque.size()); // 1应用场景双端队列常用于实现撤销操作、滑动窗口最大值问题等。## 4. 优先队列Priority Queue优先队列中的每个元素都有优先级优先级高的元素优先出队。我们使用最小堆作为底层实现。typescript// 优先队列节点interface PriorityNodeT { element: T; priority: number;}// 优先队列实现使用最小堆class PriorityQueueT { private heap: PriorityNodeT[] []; // 入队插入元素并保持堆结构 enqueue(element: T, priority: number): void { const node: PriorityNodeT { element, priority }; this.heap.push(node); this.bubbleUp(this.heap.length - 1); } // 出队移除并返回优先级最高的元素 dequeue(): T | undefined { if (this.isEmpty()) return undefined; const min this.heap[0]; const last this.heap.pop()!; if (!this.isEmpty()) { this.heap[0] last; this.sinkDown(0); } return min.element; } // 上浮操作插入时使用 private bubbleUp(index: number): void { while (index 0) { const parentIndex Math.floor((index - 1) / 2); if (this.heap[index].priority this.heap[parentIndex].priority) { break; } [this.heap[index], this.heap[parentIndex]] [this.heap[parentIndex], this.heap[index]]; index parentIndex; } } // 下沉操作删除时使用 private sinkDown(index: number): void { const length this.heap.length; while (true) { let smallest index; const leftChild 2 * index 1; const rightChild 2 * index 2; if (leftChild length this.heap[leftChild].priority this.heap[smallest].priority) { smallest leftChild; } if (rightChild length this.heap[rightChild].priority this.heap[smallest].priority) { smallest rightChild; } if (smallest index) break; [this.heap[index], this.heap[smallest]] [this.heap[smallest], this.heap[index]]; index smallest; } } isEmpty(): boolean { return this.heap.length 0; } size(): number { return this.heap.length; }}// 测试优先队列const priorityQueue new PriorityQueuestring();priorityQueue.enqueue(紧急任务, 1);priorityQueue.enqueue(普通任务, 3);priorityQueue.enqueue(次要任务, 5);priorityQueue.enqueue(重要任务, 2);console.log(\n优先队列测试:);console.log(出队顺序:);while (!priorityQueue.isEmpty()) { console.log(priorityQueue.dequeue()); // 紧急任务, 重要任务, 普通任务, 次要任务}核心思想最小堆保证根节点始终是优先级最高的元素所有操作时间复杂度为 O(log n)。## 5. 完整测试套件为了验证所有队列的正确性我们编写一个完整的测试函数typescript// 统一测试函数function testQueueT( queue: any, operations: Array{ op: string; args?: any[] }, expected: any[]): void { let result: any[] []; operations.forEach(({ op, args }) { switch (op) { case enqueue: queue.enqueue(...(args || [])); break; case dequeue: result.push(queue.dequeue()); break; case peek: result.push(queue.peek()); break; case size: result.push(queue.size()); break; case isEmpty: result.push(queue.isEmpty()); break; default: break; } }); console.log(测试结果:, JSON.stringify(result)); console.log(预期结果:, JSON.stringify(expected)); const passed JSON.stringify(result) JSON.stringify(expected); console.log(passed ? ✅ 测试通过 : ❌ 测试失败);}// 运行测试console.log( 队列通用测试 );const testQueueInstance new SimpleQueuenumber();testQueue(testQueueInstance, [ { op: enqueue, args: [1] }, { op: enqueue, args: [2] }, { op: dequeue }, { op: enqueue, args: [3] }, { op: dequeue }, { op: dequeue }, { op: isEmpty } ], [1, 2, 3, true]);## 总结通过本文的实战我们使用 TypeScript 实现了四种经典队列1.简单队列基于数组实现简单但出队效率低O(n)2.循环队列通过指针复用空间实现 O(1) 操作适合固定容量场景3.双端队列支持两端操作灵活性强4.优先队列基于最小堆保障高优先级元素优先出队在实际开发中选择哪种队列取决于具体需求- 任务调度系统优先队列- 消息中间件循环队列固定缓冲区- 编辑器撤销功能双端队列- 简单流程控制简单队列掌握这些队列的实现原理不仅能提升你的编码能力还能帮助你更好地理解操作系统、数据库等底层系统的工作原理。希望本文的代码示例能成为你日常开发中的实用参考。

相关新闻

3分钟快速上手PyTorch Geometric:构建你的第一个图神经网络

3分钟快速上手PyTorch Geometric:构建你的第一个图神经网络

3分钟快速上手PyTorch Geometric:构建你的第一个图神经网络 【免费下载链接】pytorch_geometric Graph Neural Network Library for PyTorch 项目地址: https://gitcode.com/GitHub_Trending/py/pytorch_geometric 你是否曾被复杂的图神经网络(GN…

2026/7/27 18:48:59 阅读更多 →
如何在React表单中集成Turnstile:提升安全性的完整指南

如何在React表单中集成Turnstile:提升安全性的完整指南

如何在React表单中集成Turnstile:提升安全性的完整指南 【免费下载链接】react-turnstile Cloudflare Turnstile integration for React. 项目地址: https://gitcode.com/gh_mirrors/re/react-turnstile React Turnstile是Cloudflare Turnstile在React应用中…

2026/7/27 18:48:59 阅读更多 →
Redis-Search终极指南:高性能实时前缀搜索如何革新Rails应用体验

Redis-Search终极指南:高性能实时前缀搜索如何革新Rails应用体验

Redis-Search终极指南:高性能实时前缀搜索如何革新Rails应用体验 【免费下载链接】redis-search Deprecated! High performance real-time prefix search, indexes store in Redis for Rails application 项目地址: https://gitcode.com/gh_mirrors/re/redis-sear…

2026/7/27 18:48:59 阅读更多 →

最新新闻

pkNX解决方案:宝可梦Switch游戏数据编辑与随机化技术实现

pkNX解决方案:宝可梦Switch游戏数据编辑与随机化技术实现

pkNX解决方案:宝可梦Switch游戏数据编辑与随机化技术实现 【免费下载链接】pkNX Pokmon (Nintendo Switch) ROM Editor & Randomizer 项目地址: https://gitcode.com/gh_mirrors/pk/pkNX pkNX是一款针对任天堂Switch平台宝可梦系列游戏的C#开源ROM编辑与…

2026/7/27 18:59:02 阅读更多 →
从实操维度拆解短剧出海工具价值:何为真正好用的译制方案

从实操维度拆解短剧出海工具价值:何为真正好用的译制方案

在短剧出海行业日常运营中,绝大多数从业者挑选工具的朴素诉求,就是“好用”。不同于“专业”侧重技术指标、“靠谱”侧重长期风险稳定、“排名”侧重综合层级对比,“好用”是完全贴合一线实操的体验维度,聚焦上手门槛低、适配场景…

2026/7/27 18:59:02 阅读更多 →
5分钟快速上手:用Semi-Utils为照片批量添加专业相机水印

5分钟快速上手:用Semi-Utils为照片批量添加专业相机水印

5分钟快速上手:用Semi-Utils为照片批量添加专业相机水印 【免费下载链接】semi-utils 一个批量添加相机机型和拍摄参数的工具,后续「可能」添加其他功能。 项目地址: https://gitcode.com/gh_mirrors/se/semi-utils Semi-Utils是一款专为摄影爱好…

2026/7/27 18:59:02 阅读更多 →
终极漫画阅读器指南:ACBR如何一站式管理你的数字漫画与电子书库

终极漫画阅读器指南:ACBR如何一站式管理你的数字漫画与电子书库

终极漫画阅读器指南:ACBR如何一站式管理你的数字漫画与电子书库 【免费下载链接】comic-book-reader ACBR - A comic book reader and converter for CBZ, CBR, CB7, EPUB, FB2, MOBI 7 and PDF files (Windows & Linux) 项目地址: https://gitcode.com/gh_mi…

2026/7/27 18:59:02 阅读更多 →
从零开始:用Obsidian-Templates构建你的智能知识网络

从零开始:用Obsidian-Templates构建你的智能知识网络

从零开始:用Obsidian-Templates构建你的智能知识网络 【免费下载链接】Obsidian-Templates A repository containing templates and scripts for #Obsidian to support the #Zettelkasten method for note-taking. 项目地址: https://gitcode.com/gh_mirrors/ob/O…

2026/7/27 18:59:02 阅读更多 →
树上点差分算法详解

树上点差分算法详解

1. 什么是树上点差分树上点差分是一种基于树形结构(通常是无根树)的差分算法,用于高效处理树上路径上的点权更新与查询问题。它是线性差分思想在树上的自然延伸。核心思想是:当需要对树上某条简单路径 u → v 上的所有点的点权进行…

2026/7/27 18:58:01 阅读更多 →

日新闻

【JAVA毕设源码分享】基于SpringBoot的社区智能垃圾管理系统的设计与实现(程序+文档+代码讲解+一条龙定制)

【JAVA毕设源码分享】基于SpringBoot的社区智能垃圾管理系统的设计与实现(程序+文档+代码讲解+一条龙定制)

博主介绍:✌️码农一枚 ,专注于大学生项目实战开发、讲解和毕业🚢文撰写修改等。全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围:&am…

2026/7/27 0:00:54 阅读更多 →
SPI实战指南:从时钟模式到寄存器配置,解决嵌入式通信难题

SPI实战指南:从时钟模式到寄存器配置,解决嵌入式通信难题

1. 项目概述:从寄存器手册到实战指南 如果你手头有一份类似德州仪器(TI)TMS320x240xA系列DSP的SPI模块技术手册,看着里面密密麻麻的寄存器位定义、时序图和公式,是不是感觉头大?这份资料虽然权威&#xff0…

2026/7/27 0:00:54 阅读更多 →
【JAVA毕设源码分享】基于springboot的水果购物管理系统的设计与实现(程序+文档+代码讲解+一条龙定制)

【JAVA毕设源码分享】基于springboot的水果购物管理系统的设计与实现(程序+文档+代码讲解+一条龙定制)

博主介绍:✌️码农一枚 ,专注于大学生项目实战开发、讲解和毕业🚢文撰写修改等。全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围:&am…

2026/7/27 0:00:54 阅读更多 →

周新闻

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 数据集6000张 完整源码已标注数据集训练好的模型环境配置教程程序运行说明文档,可以直接使用!系统支持图片、视频、摄像头等多种方式检测裂缝,功能强大实用。 1数据集6000张 8各类别

2026/7/27 4:33:59 阅读更多 →
深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

pubg数据集 精选原图1.42万数据 1.49万标签 无任何重复、算法增强或冗余图像! pubg绝地求生目标检测数据集 1分类:e_body,14905个标签,txt格式 共计14244张图,99%为640*640尺寸图像 适合yolo目标检测、AI训练关键词&am…

2026/7/27 6:31:56 阅读更多 →
Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex检测数据集数据集详情检测类别: allies enemy tag图片总量:7247张训练集:5139张验证集:1425张测试集:683张标注状态:全部已标注,即拿即用数据格式:支持YOLO格式及其他格式&#…

2026/7/27 4:01:12 阅读更多 →

月新闻