首页 > 编程语言 >JavaScript 链表的增删改查

JavaScript 链表的增删改查

时间:2023-06-29 10:46:27浏览次数:34  
标签:head currentNode JavaScript 改查 链表 null data 节点

 

 

 

//节点对象
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

 

标签:head,currentNode,JavaScript,改查,链表,null,data,节点
From: https://www.cnblogs.com/hechunfeng/p/17513411.html

相关文章

  • JavaScript学习 -- 内置函数(Math和Date)
    一、Date函数letdate=newDate()console.log("当前日期和时间:"+date)console.log("当前日期和时间:"+date.toLocaleString())console.log("年份:"+date.getFullYear())console.log("月份:"+(parseInt(date.getMonth())+1))console.log("日:"......
  • JavaScript引爆Salesforce职业生涯!抓住高薪机会
    Salesforce是一款领先的CRM软件,已被各种规模和行业的企业使用多年。Salesforce不仅易于使用,而且可定制,使企业能够改善其销售、营销、客户服务和其他业务流程。近年来,Salesforce一直在创新,从传统的基于Oracle的平台转变为在业界更具吸引力的解决方案。目前,许多工作可以由人工智能......
  • 143. 重排链表
    给定一个单链表L的头节点head,单链表L表示为:L0→L1→…→Ln-1→Ln请将其重新排列后变为:L0→Ln→L1→Ln-1→L2→Ln-2→…不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。示例1:输入:head=[1,2,3,4]输出:[1,4,2,3]>代码1(前......
  • JavaScript-常用字符串方法和属性
    JavaScript-常用字符串方法和属性charAt()//返回指定位置处的字符。charCodeAt()//返回指定位置处字符编码。codePointAt()//返回字符串中索引(位置)处的Unicode值。concat()//返回两个或多个连接的字符串。constructor返回字符串的构造函数。endsWith()//返回......
  • 在 Java、Python、JavaScript 和 Go 中拥抱异步
    ​本文讨论了四种语言的异步,强调了它在创建高效、响应迅速的应用程序中的作用。作为一名拥有多年主要使用Java工作经验的软件开发人员,当我最近为一个新项目切换到Python时,我发现自己很感兴趣。这种转变促使我探索各种语言的异步编程世界,包括Java、Python、JavaScript和Go......
  • 使用 SQLAlchemy 库来实现对 MySQL 数据库的增删改查
    在 Flask 中使用SQLAlchemy库来实现对MySQL数据库的增删改查fromflaskimportFlask,request,jsonifyfromflask_sqlalchemyimportSQLAlchemyapp=Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI']='mysql://username:password@localhost/dbname'ap......
  • Shuffle Cards (牛客多校) (rope 块状链表 用作可持续优化平衡树, 用于区间的整体移动
    rope:#include<ext/rope>usingnamespace__gnu_cxx; 定义方法:rope<变量类型>变量名称;人话解释:超级string算法解释:块状链表(即讲链表与数组的优势结合,形成分块思想)用途解释:这本来是一个用于快速操作string的工具,却一般被定义成int,然后用作可持久化线段树!insert(intpos,s......
  • Excel JavaScript object model in Office Add-ins
    ExcelJavaScriptobjectmodelinOfficeAdd-ins-OfficeAdd-ins|MicrosoftLearnOffice.jsAPIforExcelExcel加载项使用 OfficeJavaScriptAPI 与Excel中的对象进行交互,其中包括两个JavaScript对象模型:ExcelJavaScriptAPI:随Office2016一起引入的Exc......
  • #yyds干货盘点# LeetCode程序员面试金典:重排链表
    题目:给定一个单链表L的头节点head,单链表L表示为:L0→L1→…→Ln-1→Ln请将其重新排列后变为:L0→Ln→L1→Ln-1→L2→Ln-2→…不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 示例1:输入:head=[1,2,3,4]输出:[1,4,2,3]示例2:输入:head......
  • ELK 8.0.0 数据增删改查
    ELK8.0.0数据增删改查目录ELK8.0.0数据增删改查1创建文档数据2查找所创建的文档3更新文档中的数据4删除索引5match5.1match_all5.2match5.3match_phrase1创建文档数据PUTfcarey/_doc/1{"name":"fcarey","age":18,"city":"sz","tag&quo......