JS 链表实现

链表规则,前一个指向后一个,必须从头开始查找。
  • push pop delete get isEmpty

  • push(value): 将值添加到链表的末尾

  • pop() :弹出链表中的最后一个值

  • get(index):返回给定索引中的项

  • delete(index):从给定索引中删除项

  • isEmpty(): 返回一个布尔值,指示链表是否为空

实现代码如下:

class JsList{
    constructor(){
        this.head = null
        this.tail = null
        this.length = 0
    }
    isEmpty(){
        return this.length == 0
    }
    push(value){
        const node = Node(value)
        if(this.isEmpty()){
            node.next = null
            this.head = node
            this.tail = node
        }else{
            this.tail.next = node
            this.tail = node  
        }
        this.length++;
        return node
    }
    pop(){
        if(this.isEmpty()){
            return null
        }
        const nodeToRemove = this.tail;
        // 需找到倒数第二个节点,所以只能从头开始
        let secondToLastNode
        let currentNode = this.head
        while(currentNode){
            if(currentNode.next == this.tail){
                secondToLastNode = currentNode
                break
            }
            currentNode = currentNode.next;
        }
        secondToLastNode.next = null
        this.tail = secondToLastNode
        this.length--
        return nodeToRemove
    }
    get(index){
        //判断范围
        if(index < 0 || index > this.length){
            return null
        }
        if(this.isEmpty()){
            return null
        }
        let iterator = 0
        let currentNode = this.head
        while(iterator < index){
            iterator++
            currentNode = currentNode.next
        }
        return currentNode
    }
    delete(index){
        if(index < 0 || index > this.length){
            return null
        }
        if(this.isEmpty()){
            return null
        }
        if(index == 0){
            const nodeToDelete = this.head
            this.head = this.head.next
            this.length--
            return nodeToDelete
        }
        let previousNode
        let iterator = 0
        let currentNode = this.head
        while(iterator < index){
            iterator++
            previousNode = currentNode
            currentNode = currentNode.next
        }
        previousNode.next = currentNode.next
        if(currentNode.next == null){
            this.tail = previousNode
        }
        const noToDelete = this.head
        this.length--
        return noToDelete

    }
  }
posted @ 2020-04-17 16:47  萝卜爱吃青菜  阅读(199)  评论(0编辑  收藏  举报