JS实现队列
JS实现队列:
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头
链式队列的实现
function LinkedQueue() { let Node = function (ele) { this.ele = ele; this.next = null; } let length = 0, front, //队首指针 rear; //队尾指针 this.push = function (ele) { let node = new Node(ele), temp; if (length == 0) { front = node; } else { temp = rear; temp.next = node; } rear = node; length++; return true; } this.pop = function () { let temp = front; front = front.next length--; temp.next = null return temp; } this.size = function () { return length; } this.getFront = function () { return front; // 有没有什么思路只获取队列的头结点,而不是获取整个队列 } this.getRear = function () { return rear; } this.toString = function () { let string = '', temp = front; while (temp) { string += temp.ele + ' '; temp = temp.next; } return string; } this.clear = function () { front = null; rear = null; length = 0; return true; } } let myQueue = new LinkedQueue(); myQueue.push(1) myQueue.push(2) myQueue.push(3) myQueue.push(4) console.log(myQueue.toString()) // 1 2 3 4 console.log(myQueue.pop()) // Node { ele: 1, next: null } console.log(myQueue.toString()) // 2 3 4
顺序存储队列:利用js内置Array对象
function ArrayQueue(){ var arr = []; //入队操作 this.push = function(element){ arr.push(element); return true; } //出队操作 this.pop = function(){ return arr.shift(); } //获取队首 this.getFront = function(){ return arr[0]; } //获取队尾 this.getRear = function(){ return arr[arr.length - 1] } //清空队列 this.clear = function(){ arr = []; } //获取队长 this.size = function(){ return length; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2016-11-01 git stash压栈
2016-11-01 Array、ArrayList和List三者的区别