zoukankan      html  css  js  c++  java
  • js 链表的创建以及增删改查操作

    话说面试又失败了,今年真是坎坷的一年,女朋友跑了,工作不顺,家里催婚,大学刚毕业,大公司不要。在这个没钱没人的年纪,有点小绝望。不多说直接上代码:

    /*======定义结构======*/
    var node=function(element){
        this.element=element
        this.next=null
    }
    var linkedList=function(){
        this.head=new node("head")
        this.find=find
        this.insert=insert
        this.update=update
        this.remove=remove
    }
    /*======查找======*/
    var find=function(item){
        let currNode=this.head
        while(currNode.element!==item){
            currNode=currNode.next
        }
        return currNode
    }
    /*======插入======*/
    /**
    *newElement:一个新节点,item:链表的目标节点
    *1.查找找到目标节点,将新节点的next指向目标节点的下一个节点
    *2.将目标节点的next指向这个新节点
    */
    var insert=function(newElement,item){
        let newNode=new node(newElement)
        let currNode=this.find(item)
        newNode.next=currNode.next
        currNode.next=newNode
    }
    /*======修改======*/
    /**
    *查找到目标节点,将其element修改
    */
    var update=function(item,newItem){
        let currNode=this.find(item)
        currNode.element=newItem
    }
    /*======删除======*/
    /**
    *找到匹配节点的前一个节点,将其next指向当前节点的下一个节点,即删除当前节点
    */
    var remove=function(item){
        let currNode=this.head
        while(currNode.next!==null && currNode.next.element!==item){
            currNode=currNode.next
        }
        if(currNode.next!==null){
            currNode.next=currNode.next.next
        }
    }
    /*======测试代码======*/
    var list=new linkedList();
    list.insert('first','head')
    list.insert('second','first')
    list.insert('third','second')
    console.log(list)
    list.find('first')
    console.log(list.find('first'))
    list.update('third','three')
    console.log(list)
    list.remove('second')
    console.log(list)
  • 相关阅读:
    汇编基础概念
    linux实验小结
    乐视三合一体感摄像头开发记录
    IplImage* 格式与Mat 格式的转换
    STM32关于优先级设定的理解 NVIC_SetPriority()
    "IRQn_Type" is undefined
    串口通信实验编译没有错误,但是串口调试助手收不到数据
    SecureCRT 8版本 自用备份
    Matlab使用robot Toolbox
    开篇
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/9902836.html
Copyright © 2011-2022 走看看