前端进阶:链表的概念和应用
由代码可知我们在节点中会有上一个节点的引用以及下一个节点的引用,同时这里笔者添加了头部节点和尾部节点方便大家操作。大家可以根据自己的需求实现双向链表的功能,这里笔者提供一份自己实现的代码,可以参考交流一下: // 双向链表, 每一个元素都有一个存储元素自身的节点和指向上一个元素引用以及下一个元素引用的节点组成 function doubleLinkedList() { let Node = function(el) { this.el = el; this.previous = null; this.next = null; } let length = 0 let head = null // 用来存储头部元素的引用 let tail = null // 用来存储尾部元素的引用
// 尾部添加元素 this.append = (el) => { let node = new Node(el) if(!head) { head = node }else { tail.next = node; node.previous = tail; } tail = node; length++ }; // 插入元素 this.insert = (pos, el) => { if(pos >=0 && pos < length) { let node = new Node(el); if(pos === length - 1) { // 在尾部插入 node.previous = tail.previous; node.next = tail; tail.previous = node; length++; return true } let current = head, i = 0; while(i < pos) { current = current.next; i++ } node.next = current; node.previous = current.previous; current.previous.next = node; current.previous = node; length ++; return true }else { throw new RangeError(`插入范围有误`) } }; // 移除指定位置的元素 this.removeAt = (pos) => { // 检测边界条件 if(pos < 0 || pos >= length) { throw new RangeError(`删除范围有误`) }else { if(length) { if(pos === length - 1) { // 如果删除节点位置为尾节点,直接删除,节省查找时间 let previous = tail.previous; previous.next = null; length --; return tail.el }else { let current = head, previous = null, next = null, i = 0; while(i < pos) { (编辑:浙我家) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- Telnet是什么命令 Telnet命令的使用方法介绍
- MobTech与中移互联网强联合 北上广深4城巡回沙龙展实力
- 中文存数据库乱码
- 数据库 – 在Microsoft Access(2010)中计算年和月的年龄
- @OrderBy导致java.lang.ClassCastException:antlr.CommonT
- ClassCastException:java.math.BigInteger在连接MySQL时无
- 今晚罗老师发飙补贴:一线大牌直播半价抢
- 奥比中光为OPPO全球首款旗舰电视提供视觉解决方案,抢占智能
- vivo 5G比邻计划全面推进 价格“贴近”成本价
- 如何解决当MySQL数据库碰到Syn Flooding问题