下面我們來封裝一下js-單向藍標中的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é)點
? ? ? ? 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é)點的next指向,后一個節(jié)點的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é)點
? ? ? ? return this.removeAt(position)
}
//? 9.isEmpty方法
? ? LinkList.prototype.isEmpty=()=> {
return this.length===0
? ? }
//? ? 10.size方法
? ? LinkList.prototype.size=()=>{
return this.length
? ? }