十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
前言

前端也要搞好数据结构哦!
用JavaScript实现了个单链表,通过LinkedList构造函数可实例化一个单链表数据结构的对象,所有的方法放到LinkedList构造函数的原型对象上,写了暂时能想到的所有方法
GitHub源码地址,下载可运行
实现
方法介绍
查找
obj.find(item)通过item元素内容查找到该元素obj.findIndex(index)通过index索引查找到该元素obj.findIndexOf(item)通过item元素内容查找到该元素索引obj.findPrev(item)通过item元素查找上一个节点元素添加
obj.insert(item,newElement)在item元素后插入新元素obj.push(item)在链表末尾插入item元素obj.insertIndex(index,newElement)在index索引处插入新元素删除
obj.remove(item)删除item元素obj.removeIndex(index)删除index索引处节点其他
obj.size()返回该链表的长度obj.display()数组形式返回该链表,便于观察,测试obj.reversal()链表顺序反转(递归)方法代码
链表类LinkedList
function LinkedList (...rest) {
this._head = new Node('_head') // 链表头节点
// 如果new时有传进值,则添加到实例中
if (rest.length) {
this.insert(rest[0], '_head')
for (let i = 1; i < rest.length; i++) {
this.insert(rest[i], rest[i - 1])
}
}
}
LinkedList.prototype.find = find
LinkedList.prototype.findPrev = findPrev
LinkedList.prototype.findIndex = findIndex
LinkedList.prototype.findIndexOf = findIndexOf
LinkedList.prototype.push = push
LinkedList.prototype.insert = insert
LinkedList.prototype.insertIndex = insertIndex
LinkedList.prototype.remove = remove
LinkedList.prototype.removeIndex = removeIndex
LinkedList.prototype.size = size
LinkedList.prototype.display = display
LinkedList.prototype.reversal = reversal