前端进阶:链表的概念和应用
由代码可知我们在节点中会有上一个节点的引用以及下一个节点的引用,同时这里笔者添加了头部节点和尾部节点方便大家操作。大家可以根据自己的需求实现双向链表的功能,这里笔者提供一份自己实现的代码,可以参考交流一下: // 双向链表, 每一个元素都有一个存储元素自身的节点和指向上一个元素引用以及下一个元素引用的节点组成 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) { (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |