Prepend – LinkedList

Today I’m going to do a quick entry about prepending a linked list (adding something at the beginning). You’re probably familiar with how I’ve been going through this, so tests first!

  describe 'prepend' do
    it 'adds something at the beginning' do
      list = LinkedList.new
      list.append("B")
      list.append("C")
      list.append("D")
      expect(list.stringify).to eq("B, C, D")
    end
  end

The idea is, “Oops, I forgot that A is at the beginning of the alphabet”. This test should pass with no changes. But, I will add this to test prepend

      list.prepend("A")
      expect(list.stringify).to eq("A, B, C, D")

So now the full test is

  describe 'prepend' do
    it 'adds something at the beginning' do
      list = LinkedList.new
      list.append("B")
      list.append("C")
      list.append("D")
      expect(list.stringify).to eq("B, C, D")
      list.prepend("A")
      expect(list.stringify).to eq("A, B, C, D")
    end
  end

And that fails, because prepend is an undefined method. So we will go over to that class and make it a method.

First, I need a new node.

  def prepend(data)
    new_node = Node.new(data)
  end

Next, I’m going to need to take the current head, and make it the next_node of this new_node, and immediately after that, set the new_node to be the head.

  def prepend(data)
    new_node = Node.new(data)
    new_node.next_node = head
    @head = new_node
  end

And that is it, the test passes. Nice and simple!


Comments

2 responses to “Prepend – LinkedList”

  1. […] I want to add something to catch it if something is written to be inserted at 0. That is the prepend method, so we can take care of that […]

Leave a Reply

Discover more from Brendan Bondurant

Subscribe now to keep reading and get access to the full archive.

Continue reading