Skip to content

Instantly share code, notes, and snippets.

@jamesdabbs
Created June 22, 2016 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesdabbs/3f89740cafda72f962e080977b18a088 to your computer and use it in GitHub Desktop.
Save jamesdabbs/3f89740cafda72f962e080977b18a088 to your computer and use it in GitHub Desktop.
Element = Struct.new :datum, :next do
def tail?
!self.next
end
end
class SimpleLinkedList
attr_reader :size, :head
def self.from_a values
new.tap do |ll|
Array(values).reverse.each { |n| ll.push n }
end
end
def initialize
@size = 0
end
def empty?
!@head
end
def push val
@size += 1
@head = Element.new val, @head
end
def peek
@head && @head.datum
end
def pop
return unless @head
@head.datum.tap do
@head = @head.next
@size -= 1
end
end
def to_a
reduce([]) { |acc, n| acc.push n }
end
def reverse
reduce(SimpleLinkedList.new) { |acc, n| acc.push n }
end
# N.B. not using this for gainz, but ...
# def size
# reduce(0) { |acc, _| acc += 1 }
# end
def reduce acc
node = @head
while node
yield(acc, node.datum)
node = node.next
end
acc
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment