Data Structures: Singly Linked List Part Five

Insert

In my previous post we went over the get and set method for the singly linked list in javascript. A Singly Linked List as I mentioned in part one of this series on Linked Lists, is a data structure similar to an array. In this post we will be going over the Insert method which is similar to the set method. Similar to set we are selecting a specific node, but instead of updating the selected node, we are inserting a new node in its position and setting the selected node as the next target for the selected node.

How does the insert method

The insert method takes in two arguments, the index, and the value we are inserting. If the index is less than 0 or greater than the length of the linked list, the output will return false, because we can’t insert something into the part of a list that does not exist. However, if the index is the same as the length of the list, insert will utilize the push method previously created to push a new node to the end of the list . And likewise if the index is 0, we will use the unshift method to insert a new node to the start of the list. Otherwise, using the get method, we will select the node at the index of -1.

insert(index, value){
if (index < 0 || index > this.length) return false
if (index === this.length){
this.push(value)
return true
}
if (index === 0){
this.unshift(value)
return true
}
let newNode = new Node(value)
let prev = this.get(index - 1)
let temp = prev.next
prev.next = newNode
newNode.next = temp
this.length ++
return true;
}
}

A Software Engineer with a background in Education Technology and Dance. Recent grad form FlatIron Bootcamp, and passion for the arts and working with databases

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store