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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM