编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
class LinkNode{
    constructor(val,next){
        this.val = val;
        this.next = next;
    }
}
var myLinkedList = function(){
    this._size = 0;
    this._tail = null;
    this._head = null;
}

//查找第n个节点
myLinkedList.prototype.getNodeByIndex= function(index){
    if(index<=0 || index>this._size){
        return null;
    }
    let cur = this._head;
    while(index>1){
        cur = cur.next;
        index--;
    }
    return cur;
}
//查找第n个节点的值
myLinkedList.prototype.getValueByIndex=function(index){
    if(index<=0 || index>this._size){
        return -1;
    }
    let cur = this._head;
    while(index>1){
        cur = cur.next;
        index--;
    }
    return cur.val;
}
//头部插入节点
myLinkedList.prototype.addAtHead = function(val){
    let node = new LinkNode(val,this._head);
    this._head = node;
    this._size ++;
    if(!this._tail){
        this._tail = this._head;
    }
}
//尾部插入节点
myLinkedList.prototype.addAtTail = function(val){
    let node = new LinkNode(val,null);
    if(!this._head){
        this._head = node;
    }else{
        this._tail.next = node;
    }
    this._tail = node;
    this._size ++; 
}
//在第n个节点之后插入新节点
myLinkedList.prototype.addAtIndex = function (index,val){
    if(index<=0 || index>this._size){
        return null;
    }
    let cur = this.getNodeByIndex(index)
    let node = new LinkNode(val,cur.next);
    cur.next = node;
    if(index === this._size){
        this._tail = node
    }
    this._size++;
}
//展示成列表
myLinkedList.prototype.print = function(){
    let list = [];
    let cur = this._head;
    while(cur!=null){
        list.push(cur.val);
        cur = cur.next;
    }
    return list
}
let myList = new myLinkedList();
myList.addAtHead(1);
myList.addAtIndex(1,2);
myList.addAtTail(3);
myList.addAtHead(0);
myList.addAtTail(5);
myList.addAtIndex(4,4)
console.log(myList.print());