编辑代码

class Linked{
    constructor(){
        this.head = null;
        this.length = 0;
    }
    //获取元素
    getElementAt(position){
        if(position < 0 || position > this.length) return null;
        let _current = this.head;
        for(let i = 0; i< position; i++){
            _current = _current.next;
        }
        return _current;
    }
    //append 元素
    appendElement(ele){
        let _current = new Node(ele);
        let originLastEle = this.getElementAt(this.length - 1);
        if(!this.head){
            this.head = _current;
        }else{
            originLastEle.next = _current;
        }
        this.length++;
        return _current;
    }
    //insert 元素
    insertElement(ele, position){
         if(position < 0 || position > this.length) return false;
         let _current = new Node(ele);
         let _previous = this.getElementAt(position - 1);
         if(position === 0){
             _current.next = this.head;
             this.head = _current;
         }else {
             _current.next = _previous.next;
             _previous.next = _current;
         }
         this.length++;
         return true;
    }
    //remove 元素
    removeElement(ele, position){
        if(position < 0 || position > this.length) return false;
        let _current = new Node(ele);
        let _previous = this.getElementAt(position - 1);
        if(position === 0){
             this.head = head.next;
         }else {
             _previous.next = _current.next;
         }
         this.length--;
         return true;
    }
}

class Node{
    constructor(ele){
        this.element = ele;
        this.next = null;
    }
}

const linkedObj = new Linked();
linkedObj.insertElement('aa', 0);
linkedObj.appendElement('bb');
linkedObj.removeElement('bb', 1);
console.log(linkedObj);