Skip to content

Instantly share code, notes, and snippets.

@kronos
Created May 22, 2012 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kronos/2767177 to your computer and use it in GitHub Desktop.
Save kronos/2767177 to your computer and use it in GitHub Desktop.
class LinkedList
include Enumerable
attr_reader :head
class Node
attr_reader :value
attr_accessor :next
def initialize(value, _next = nil)
@value = value
@next = _next
end
def inspect
value.inspect
end
end
def initialize(ary = nil)
@head = Node.new(nil) # head element
@last = @head
if ary
ary.each {|value| add(value)}
end
self
end
def insert_after(where, value)
value = Node.new(value, where.next)
where.next = value
@last = value if where == @last
value
end
def each
p = @head.next
while p
yield p.value
p = p.next
end
self
end
def add(value)
insert_after(@last, value)
end
def inspect
to_a.inspect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment