class LinkNode{
constructor(val,next){
this.val = val;
this.next = next;
}
}
var myLinkedList = function(){
this._size = 0;
this._tail = null;
this._head = null;
}
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;
}
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 ++;
}
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());