数据结构_单向链表结构
//链表结构 //封装节点 class Node { constructor (data) { this.data = data this.next = null } } class LinkList { constructor () { //初始化,空链表,长度为0 this.head = null this.length = 0 } //追加数据 append (data) { // 创建新节点 let node = new Node(data) // 当前为空链表 if (!this.head) { // 让head指向新节点 this.head = node }else { // 找到尾节点 let current = this.head while (current.next) { current = current.next } current.next = node } this.length++ } // 插入数据 insert (posi, data) { // 判断position是否合法 if (posi < 0 || posi > this.length) return false let node = new Node(data) if (posi == 0) { node.next = this.head this.head = node }else { let current = this.head let index = 0 while (index++ < posi - 1) { current = current.next } node.next = current.next current.next = node } this.length++ return true } // 查找数据 indexOf (data) { let current = this.head let index = 0 while (current) { if (current.data === data) { return index } index++ current = current.next } return -1 } // 移除指定位置数据 removeAt (posi) { // Number.isInteger()判断是否为整数 if (posi < 0 || posi > this.length -1) return false if (posi == 0) { this.head = this.head.next }else { let current = this.head let index = 0 while (index++ < posi - 1) { current = current.next } current.next = current.next.next } this.length-- return true } remove (data) { //删除所有data的数据 while (this.indexOf(data) != -1) { //删除第一个出现的data数据 this.removeAt(this.indexOf(data)) } return true } isEmpty () { return this.head == null } size () { return this.length } } var list = new LinkList() list.append(1) list.append(2) list.append(3) list.insert(0, 0) list.insert(4, 4) list.insert(0, 'b') list.insert(3, 'b') list.insert(5, 'b') console.log(list) console.log(list.indexOf('b')) list.remove('b')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!