Thoughts

Singly Linked List - Insert and Remove

July 26, 2020

In this final blog on Singly-Linked-Lists, I am going to give a quick walk-through on inserting a node in the middle of a list and then removing a node from the middle of the list.

In order, to insert a node, we are going to need to pass in both the new value we are creating as well as the index where to insert it.

When creating insert we can really take advantage of our already created methods.

  1. Since we already have a method to add to the beginning(unshift) or end(push) of a list, if we are trying to insert at the beginning or end of the list, we can just run unshift or push.
  2. We can access where to insert the new node by using our get method!

Anyways here’s the syntax, and then I’ll walk through it.

 insert(index,val){
        if(index < 0 || index > this.length) return false 
        // double bang to return boolean
        if(index === this.length) return !!this.push(val)
        if(index === 0) return !!this.unshift(val)

        let prevNode = this.get(index-1)
        let nextNode = prevNode.next
        const newNode = new Node(val)
        prevNode.next = newNode
        newNode.next = nextNode
        this.length++
        return true
    }

We can use our get method to create both insert and remove


  1. Cover those edge cases!!! If the index doesn’t exist in the list, return false. If it is the first or last index, then simply run push or unshift. NOTE: I used the double bang in order to return true if the method worked properly.
  2. Set a variable to the node before the index using our get method.
  3. Set a variable to the node after that one.
  4. Create our new node with the value passed in.
  5. Insert our new node between those variables.
  6. Increase the length by 1
  7. Return true if successful.

Removing a node is almost identical to inserting, except for well removing instead of adding.

Here syntactically.

    remove(index){
        if(index < 0 || index > this.length) return undefined
        if(index === 0) return !!this.shift()
        if(index === this.length-1) return !!this.pop()
        let prevNode = this.get(index-1)
        let removedNode = prevNode.next
        prevNode.next = removedNode.next
        this.length--
        return removedNode
    }

Pretty much the same as insert but just running the opposite methods, and when accessing the previous node, just set the next node to skip one. In a linked list the only connection of one node to another is through each node’s next value, by removing that value, that node is essentially deleted.

That’s it for linked-lists!


Written by Baruch Phillips a software developer in Brooklyn.
LinkedIn -GitHub

About Me