Last active
May 5, 2018 19:00
-
-
Save airled/35e514cfebf72e58117266f71c511e1a to your computer and use it in GitHub Desktop.
Linked List in crystal
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 List(T) | |
class Node(T) | |
property :value | |
property :next | |
def initialize(@value : T, @next : List::Node(T) | List::EmptyNode) | |
end | |
end | |
class EmptyNode | |
def value | |
end | |
def next | |
self | |
end | |
end | |
def initialize | |
@head = (List::EmptyNode.new).as(List::Node(T) | List::EmptyNode) | |
end | |
def prepend(value) | |
new_node = List::Node(T).new(value, @head) | |
@head = new_node | |
end | |
def decompose | |
{@head.value, @head.next} | |
end | |
def inspect | |
result = [] of String | |
current = @head | |
while current.class != List::EmptyNode | |
result << current.value.to_s | |
current = current.next | |
end | |
"List[" + result.join(",") + "]" | |
end | |
end | |
list = List(Char | Int32).new | |
list.prepend('a') | |
list.prepend('b') | |
list.prepend('c') | |
list.prepend(10) | |
p list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment