Data Structures: Singly Linked List Part Five

Stephen Galvan
2 min readMay 14, 2021

--

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.

Using the get method, inside of select, we are going into the list and selecting the node that comes directly before the node (index -1) at the index that was entered into the insert method. For example if we have a linked list that looks like this : 0,1, 2, 3, 4, 5, and we wanted to insert 7 at index 2 which would be the value 2 in this list, the get method will isolate index-1 or 1, then create a new node with the value 7. Next it will set 7 as the .next for 1 and will set 23 as the .next for 7. Finally we need to increment the list length and return true.

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;
}
}

Below I will insert the entire code we have created thus far:

For previous the previous parts of this blog, click the links below:
Part One: Singly Linked Lists and the Push Method
Part Two: Singly Linked Lists and the Pop Method
Part Three: Singly Linked Lists and the Shift and Unshift Method
Part Four: Singly Linked Lists and the Get and Set Method

Coming up next we will go over the remove method.

--

--

Stephen Galvan
Stephen Galvan

Written by Stephen Galvan

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