Skip to content

Instantly share code, notes, and snippets.

@airled
Last active May 5, 2018 19:00
Show Gist options
  • Save airled/35e514cfebf72e58117266f71c511e1a to your computer and use it in GitHub Desktop.
Save airled/35e514cfebf72e58117266f71c511e1a to your computer and use it in GitHub Desktop.
Linked List in crystal
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