Simple Linked List order

Hi,

I was working on the simple linked list exercise and I couldn’t help to wonder whether this assertion was correct?

In my opinion, when adding an element to the list with the following code:

list = SimpleLinkedList.new
first = Element.new(1)
second = Element.new(2)
third = Element.new(3)
list.push(first).push(second).push(third)

I should get that :
=> [1, 2, 3]

in other word the assertion should be this:
assert_equal [1, 2, 3], list.to_a

I haven’t finished the exercise yet but I’m curious to get your opinion on it. Thank you.

How did you implement SimpleLinkedList?

If a SimpleLinkedList only has a head attribute, then push and pop can only manipulate the list’s head, and the test results occur naturally.

So far, I got the following:

class Element
  def initialize(value)
    @datum = value
  end

  def datum
    @datum
  end

  def next
    @next
  end

  def next=(element)
    @next = element
  end
end

class SimpleLinkedList
  def initialize(array=nil)
    if array.nil?
      @list = Array.new
    else
      @list = array.map { |e| Element.new(e) }
    end
    @size = @list.size
  end

  def list
    @list
  end

  def size
    @size
  end

  def size=(value)
    @size = value
  end

  def to_a
    list.map(&:datum)
  end
  
  def push(element)
    list[size] = element
    @size += 1
  
    self
  end

  def pop
    list.last
  end

  def reverse!
    self.to_a.reverse!
  end
end

I’ll refer you to https://en.wikipedia.org/wiki/Linked_list#Linked_list_operations

1 Like

Related github pull request https://github.com/exercism/ruby/issues/1743.

1 Like

Appreciate your feedback @glennj and @kotp.

Regarding the exercise, my tests are green but it doesn’t the exercise is done yet. Going back it. Thank you so much again to both of you.

1 Like