双向链表-常见操作(insert,get,indexOf,update)


掌握常见的insert方法

// 5.insert方法

    DoublyLinkedList.prototype.insert=(position,data)=>{

//    1.越界判断

        if (position<0||position>this.length)return false

    //    2.根据data插入新的节点

        let newDate=new Node(data)

//    3.判断原来的列表是否为空

        if (this.length===0){

this.head=newDate

this.tail=newDate

}else if (position===0){//判断插入的position是否为

            //这里插入的是第一个位置,所以只需要改变head的值!

            this.head.prev=newDate

newDate.next=this.head

            this.head=newDate

}else if (position===this.length){//判断插入的位置position在最后面

            this.tail.next=newDate

newDate.prev=this.tail

            this.tail=newDate

}else {//insert到中间的节点上

            let index=0

            let current=this.head

            while (index++ < position){

current=current.next

            }

//    修改指针

            newDate.next=current

newDate.prev=current.prev

            current.prev.next=newDate

current.prev=newDate

}

//    length千万不要忘了

        this.length +=1

        return true

    }

//  6.get方法

    DoublyLinkedList.prototype.get=(position)=>{

//    1.越界判断(有关位置的一般都要进行越界判断!)

    //    2.获取元素if (position<0||position>=this.length) return  false

        let current=this.head;

        let index=0

    //    3.遍历循环获取元素值

        while(index++

current=current.next

        }

return current.data

    }

//  7.indexOf方法

    DoublyLinkedList.prototype.indexOf=(data)=>{

//定义变量

        let current=this.head

        let index=0

        while (current){

if (current.data===data){

//这里返回的下标从0开始!

                return index

}

current=current.next

            index++

}

//-1表示的遍历了所有链表都没有找到

        return -1

    }

//  8.update方法

    DoublyLinkedList.prototype.update=(position,date)=>{

//    1.越界判断

        if (position<0||position>=this.length) {

return false

        }

//    2.遍历寻找正常的节点

        let current=this.head

        let index=0

        while (index++

current=current.next

        }

//  3.找到之后,更新所需要的节点

        current.data=date

// return true

      return true

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。