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)
  • 相关阅读:
    路飞学城Python-Day4(practise)
    事件绑定和普通事件的区别
    数组中shift(),push(),unshift(),pop()方法
    IE6中常见BUG与相应的解决办法
    apply()与call()的区别
    CSS引入的方式有哪些? link和@import的区别是?
    substring() , slice() and substr()方法
    webpack常用命令总结
    webpack
    从输入URL 到页面加载完成的过程
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/9902836.html
Copyright © 2011-2022 走看看