Created
May 22, 2012 06:53
-
-
Save kronos/2767177 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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