Sha256: 6555e9faa4efcf6d943f2cda2f4296e04a1c0687e6ccfc64d306bca8fce9c086

Contents?: true

Size: 1003 Bytes

Versions: 50

Compression:

Stored size: 1003 Bytes

Contents

class Element
  attr_reader   :datum
  attr_accessor :next

  def initialize(datum, next_element=nil)
    @datum = datum
    @next  = next_element
  end

  def tail?
    @next.nil?
  end
end

class SimpleLinkedList
  attr_reader :size
  attr_reader :head

  def initialize
    @head = nil
    @size = 0
  end

  def push(datum)
    e = Element.new(datum, @head)
    @head = e
    @size += 1
  end

  def empty?
    @size.zero?
  end

  def peek
    @head.nil? ? nil : @head.datum
  end

  def pop
    e, @head = @head, @head.next
    @size -= 1
    return e.datum
  end

  def each
    return enum_for(:each) unless block_given?
    current = head
    until current.nil?
      yield current.datum
      current = current.next
    end
  end

  def to_a
    each.to_a
  end

  def reverse
    each.with_object(SimpleLinkedList.new) { |datum, list| list.push(datum) }
  end

  def self.from_a(a)
    new.tap do |list|
      a.to_a.reverse_each do |item|
        list.push(item)
      end
    end
  end
end

Version data entries

50 entries across 50 versions & 1 rubygems

Version Path
trackler-2.0.5.13 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.12 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.11 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.10 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.9 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.8 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.7 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.6 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.5 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.4 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.3 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.2 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.1 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.5.0 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.4.0 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.3.9 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.3.8 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.3.7 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.3.6 tracks/ruby/exercises/simple-linked-list/example.rb
trackler-2.0.3.5 tracks/ruby/exercises/simple-linked-list/example.rb