Created
June 22, 2016 00:20
-
-
Save jamesdabbs/3f89740cafda72f962e080977b18a088 to your computer and use it in GitHub Desktop.
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
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