js-單向鏈表(insert,get,indexOf,update)

在上一節(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

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容