JS-單向鏈表(removeAt,remove,isEmpty,size)

下面我們來封裝一下js-單向藍(lán)標(biāo)中的removeAt,remove,isEmpty,size方法

// 7.removeAt方法-傳入位置,返回刪除的數(shù)據(jù)!

? ? LinkList.prototype.removeAt=(position)=>{

//? ? 有的刪除操作會將刪除的數(shù)據(jù)返回,所以return current.data,如何不刪除,正常的返回true就可以啦!

? ? //? 1.越界判斷

? ? ? ? if (position<0||position>=this.length)return null

? ? //? 2.判斷是否是刪除的第一個節(jié)點(diǎn)

? ? ? ? let current=this.head

? ? ? ? if (position===0){

this.head=this.head.next

? ? ? ? }else{

let index=0

? ? ? ? ? ? let previous=null

? ? ? ? ? ? while (index++

previous=current;

? ? ? ? ? ? ? ? current=current.next

? ? ? ? ? ? }

//? ? 將前一個節(jié)點(diǎn)的next指向,后一個節(jié)點(diǎn)的next

? ? ? ? ? ? previous.next=current.next;

? ? ? ? }

//? ? 3.最后千萬不要忘記了length—1

? ? ? ? this.length-=1

? ? ? ? return current.data

? ? }

//? 8.remove方法-刪除數(shù)據(jù)

? ? LinkList.prototype.remove=(data)=>{

//? ? 1.獲取data數(shù)據(jù)在鏈表中的位置

? ? ? ? let position=this.indexOf(data)

//? 2.根據(jù)位置信息刪除節(jié)點(diǎn)

? ? ? ? return this.removeAt(position)

}

//? 9.isEmpty方法

? ? LinkList.prototype.isEmpty=()=> {

return this.length===0

? ? }

//? ? 10.size方法

? ? LinkList.prototype.size=()=>{

return this.length

? ? }

?著作權(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)容