JavaScript 链表的增删改查
//节点对象 class Node{ constructor(data){ this.data=data;//存储节点数据 this.next=null;//存储下一个节点的引用,默认为null } } //链表对象 class LinkedList{ constructor(){ this.head=null;//链表头节点,默认为null } //向链表末尾添加节点 append(data){ const newNode=new Node(data) if(this.head===null){ //如果链表为空,将新节点设置为头节点 this.head=newNode; }else{ let currentNode=this.head; //找到节点的末尾 while(currentNode.next!==null){ currentNode=currentNode.next; } //在末尾添加新节点 currentNode.next=newNode } } // 打印链表元素 print(){ let currentNode=this.head; let output=''; while(currentNode!==null){ output+=`${currentNode.data}->`; currentNode=currentNode.next; } output+=`null` console.log(output) } //在指定位置插入节点 insertAt(positon,data){ const newNode=new Node(data); if(positon===0){ //如果要在头部插入节点 newNode.next=this.head this.head=newNode; }else{ let count=0; let previousNode=null; let currentNode=this.head; //找到要插入位置的节点和前一个节点 while(count<positon){ count++; previousNode=currentNode currentNode=currentNode.next; } //指定位置插入节点 newNode.next=currentNode; previousNode.next=newNode } } //从链表中删除指定位置的节点 removeAt(positon){ if(this.head===null){ return;//如果链表为空,直接返回 } let count=0; let previousNode=null; let currentNode=this.head; //找到要删除位置的节点和前一个节点 while(count<positon){ if(currentNode===null){ return;//如果链表长度不足将删除位置,直接返回 } count++; previousNode=currentNode; currentNode=currentNode.next; } if(previousNode===null){ //如果要删除的是头节点 this.head=currentNode.next; }else{ previousNode.next=currentNode.next; } } //获取节点的长度 size(){ let count =0; let currentNode=this.head; while(currentNode!==null){ count++; currentNode=currentNode.next; } return count; } } const linkedList = new LinkedList(); linkedList.append(10); linkedList.append(20); linkedList.append(30); linkedList.print(); // 输出: 10 -> 20 -> 30 -> null linkedList.insertAt(1, 15); linkedList.print(); // 输出: 10 -> 15 -> 20 -> 30 -> null linkedList.removeAt(2); linkedList.print(); // 输出: 10 -> 15 -> 30 -> null console.log(linkedList.size()); // 输出: 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现