Linked List Class

Now that a node exists, it’s time to start building it out so that you can make a Linked List. A linked list is a collection of nodes, so you will need to make a new class and new tests.

First, just do a simple test to make sure that it exists.

RSpec.describe LinkedList do
  describe 'initialize' do
    it 'exists' do
      list = LinkedList.new
      expect(list).to be_instance_of(LinkedList)
    end
  end

If you run it, you should get an uninitialized constant error because there is no linked list class yet. So make that first, and this is honestly all you need to make that test pass.

class LinkedList
end

For a linked list to work, it has to start somewhere, and usually, the first node in the list is referred to as the head. Here is a way to test to make sure that the head exists and it has nothing in it.

    it 'has a head' do
      list = LinkedList.new
      expect(list.head).to eq(nil)
    end

And if you run that, you should get an undefined method head for LinkedList. So you’re going to want to initialize it, assign an instance variable for @head, and add an attr_reader to allow @head to be accessed.

class LinkedList
  attr_reader :head
  def initialize
    @head = nil
  end
end

And now that should pass. I will add one more method I use in this that will come in handy later before I write about adding/taking things away from the linked list. We’ll stay in the linked list class for the first one. We’re going to add an empty? method, which will test if @head = nil. We will only test that it tells us true if @head = nil, but we will test for false after adding the append method.

  describe '#empty?' do
    it 'it is empty' do
      list = LinkedList.new
      expect(list.empty?).to eq(true)
    end
  end

I put this in a new describe block because it is a new method. If you run it, you’ll get an undefined method 'empty?' error. So, head over to the class and make a method.

  def empty?
    head.nil? 
  end

The test should pass now; you’re ready to add stuff next time.


Comments

Leave a Reply

Discover more from Brendan Bondurant

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

Continue reading