Skip to content

Instantly share code, notes, and snippets.

@nicooga
Last active June 11, 2016 22:15
Show Gist options
  • Save nicooga/a0313a9a9762d5327d4a6cf15240d08c to your computer and use it in GitHub Desktop.
Save nicooga/a0313a9a9762d5327d4a6cf15240d08c to your computer and use it in GitHub Desktop.
require "awesome_print"
module LinkedList
class Node < Struct.new(:head, :tail)
undef :head=
undef :tail=
end
def self.unshift(list, el)
Node.new(el, list)
end
def self.shift(list)
list.tail
end
def self.push(list, el)
case list.tail
when Node then Node.new(list.head, push(list.tail, el))
when NilClass then Node.new(list.head, Node.new(el))
end
end
#def pop(list, el)
#case tail
#when nil then nil
#when LinkedList then tail
#end
#end
end
class << LinkedList
def from_ary(ary)
ary.reverse_each.inject(nil) do |memo, element|
memo = self::Node.new(element, memo)
end
end
end
ap ll = LinkedList.from_ary([1,2,3])
ap LinkedList.unshift ll, 0
ap LinkedList.push ll, 4
ap LinkedList.shift ll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment