在上一節(jié)的基礎(chǔ)上,我們來學(xué)習(xí)單向鏈表的insert,get,idnexOf,update操作
LinkList.prototype.insert=(position,data)=>{
// 1.對越界的position進(jìn)行判斷
//? 對長度的判斷
? ? if (position<0||position>this.length)return false
//? ? 根據(jù)data 創(chuàng)建節(jié)點(diǎn)
? ? let newNode=new Node()
//? ? 判斷插入的位置是否是第一個(gè)
//? ? position代表的是下標(biāo)值!
? ? if (position===0){
//這個(gè)可以畫圖理解,第一個(gè)節(jié)點(diǎn)為1,插入到第一個(gè)節(jié)點(diǎn)的時(shí)候,我們這樣想
? ? ? ? //原來的this.head指針指向的是原來的第一個(gè)節(jié)點(diǎn),我們現(xiàn)在將指針指向的原來的第一個(gè)節(jié)點(diǎn)賦值給新節(jié)點(diǎn)
? ? ? ? //在這個(gè)過程中,head的指針并不會發(fā)生變化,我再將head指向新節(jié)點(diǎn),畫圖參考想,好理解!
? ? ? ? // 這樣我們就實(shí)現(xiàn)了插入第一個(gè)節(jié)點(diǎn)的過程
? ? ? ? newNode.next=this.head;
? ? ? ? this.head=newNode
}else {
let index =0//下標(biāo)
? ? ? ? let current =this.head//確認(rèn)要插入的位置,比如插入在第6的位置,這個(gè)current代表的是6,
? ? ? ? let previous =null
? ? ? ? //我們就要插入的就是在6之前5之后,5用previous表示
? ? ? ? while (index++ < position) {
//在進(jìn)行插入之前,previous總是在current的前一位
? ? ? ? ? ? previous = current
current = current.next
? ? ? ? }
newNode.next = current
previous.next = newNode
}
//? ? 4.length
? ? this.length+=1
}
// 4.get方法
? ? LinkList.prototype.get=(position)=>{
// 1.越界判斷
? ? ? if (position<0||position>this.length)return null
? //? 2.獲取對應(yīng)的data
? ? ? let current=this.head;
? ? ? let index=0;
? ? ? while (index++
current=current.next
? ? ? }
return current.data
? }
//? 5.indexOf方法
? ? LinkList.prototype.indexOf=(data)=>{
//? ? 1.定義變量
? ? ? ? let current=this.head;
? ? ? ? let index=0
? ? //? ? 2.查找變量
? ? ? ? while (current){
if (current.data===data){
return index
}
current=current.next
? ? ? ? ? ? index++;
? ? ? ? ? ? //? ? 3.未查找到返回-1
? ? ? ? }
return -1
? ? }
//? 6.updata方法
? ? LinkList.prototype.update=(position,newData)=>{
//? 1.越界判斷
? ? ? ? if (position<0||position>=this.length)return false
? ? //? 2.查找判斷
? ? ? ? let current=this.head;
? ? ? ? let index=0;
? ? ? ? while(index++
current=current.next
? ? ? ? }
//3.將position位置的node上的data更新為newData
? ? ? ? current.data=newData
return true
? ? }
}