Created
December 17, 2014 21:13
-
-
Save jin/e516bb903e0fdf186a9a to your computer and use it in GitHub Desktop.
Implementing Linked List with structs
This file contains 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
Node = Struct.new(:val, :next_node) do | |
def length | |
return 1 if next_node.nil? | |
1 + next_node.length | |
end | |
def to_s | |
self.to_a.join(", ") | |
end | |
def to_a | |
return [val] if next_node.nil? | |
[val] + self.next_node.to_a | |
end | |
def add value | |
if self.next_node.nil? | |
self.next_node = Node.new(value, nil) | |
else | |
self.next_node.add value | |
end | |
end | |
def index_of value, i = 0 | |
return i if val == value | |
return -1 if next_node.nil? | |
next_node.index_of value, i + 1 | |
end | |
end | |
n1 = Node.new(1, nil) # => #<struct Node val=1, next_node=nil> | |
n1.to_a # => [1] | |
n1.add(2) # => #<struct Node val=2, next_node=nil> | |
n1.to_a # => [1, 2] | |
n1.add(3) | |
n1.to_a # => [1, 2, 3] | |
n1.add("foo") | |
n1.add("bar") | |
n1.to_a # => [1, 2, 3, "foo", "bar"] | |
n1.length # => 5 | |
n1.index_of "foo" # => 3 | |
n1.to_s # => "1, 2, 3, foo, bar" | |
n1.index_of 4 # => -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment