双向链表-常见操作(remove等其他的方法)

这里我们封装的是removeAt,remove,isEmpty方法,size方法,获取第一个节点,最后一个节点.

// 9.removeAt方法

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

//    1.越界判断

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

        let current=this.head

        //首先判断长度是否为0

        if (this.length===1){

this.head=null

            this.tail=null

        //其次,有长度后,我们需要判断的是删除的位置

        //    先判断删除的位置是否是第一个位置和最后的位置

        //    然后在判断插入放入位置在中间的情况!

        }else{

if (position===0){//2.判断是否只有一个节点

                this.head.next.prev=null

                this.head=this.head.next

            }else if (position===this.length-1){//判断要删除的节点是最后一个节点

                current=this.tail

                this.tail.prev.next=null

                this.tail=this.tail.prev

            }else{

//确定要删除的节点在中间!

                let index=0

                //    确定要删除节点的位置

                while (index++

current=current.next

                }

//    删除节点

                current.next.prev=current.prev

                current.prev.next=current.next

            }

}

//length-1

        this.length -=1

        return current.data//返回被删除节点的数据!

    }

//  10.remove方法

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

//    1.根据data获取索引值

        let index=this.indexOf(data)

//    2.根据索引值删除对应的节点

        return this.removeAt(index)

}

//  11.isEmpty方法

    DoublyLinkedList.prototype.isEmpty=()=>{

return this.length ===0

    }

// 12.size方法

    DoublyLinkedList.prototype.size=()=>{

return this.length

    }

// 13.获取链表的第一个节点

    DoublyLinkedList.prototype.getHead=()=>{

return this.head.data

    }

//14.获取链表的最后一个节点!

    DoublyLinkedList.prototype.getTail=()=>{

return this.tail.data

    }

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