本篇的完整程式碼在這裡
原本的 array method 並沒有 insertAt & removeAt
如果要 insert element into specific index 詳情請看這裡
不過這裡來為 Linked List 繼續添加 insertAt/removeAt 的 method
好讓我們可以從 特定位置新增/移除 Node
insert new Node at specific value of index
insertAt 這邊分成幾種可能來看
unshift在做的事push在做的事 insertAt(value, index) {
     if (index > this.length || index < 0) {
         return null;
     }
     if (index === 0) {
         this.unshift(value);
         return;
     } else if (index === this.length) {
         this.push(value);
         return;
     }
     let newNode = new Node(value);
     let currentNode = this.head;
     for (let i = 1; i < index; i++) {
         currentNode = currentNode.next;
     }
     newNode.next = currentNode.next;
     currentNode.next = newNode;
}
remove Node at specific index
removeAt 這邊分成幾種可能來看
shift在做的事pop在做的事removeAt(index) {
          if (index < 0 || index > this.length - 1) {
            return null;
          } else if (index === 0) {
            this.shift();
          } else if (index === this.length - 1) {
            this.pop();
          } else {
            let currentNode = this.head;
            for (let i = 1; i < index - 1; i++) {
              currentNode = currentNode.next;
            }
            let temp = currentNode.next;
            currentNode.next = temp.next;
            this.length--;
            return;
          }
}
get value of Node at specific position
get(index){
    if(index>this.length || index <0){
        return;
    }else{
        let currentNode = this.head;
        for(let i =1;i<=index;i++){
            currentNode = currentNode.next;
        }
        return currentNode.value;
    }
}
這樣寫完一輪,是不是對 Linked List 跟 Node 之間更有概念了呢?