Skip to content

Instantly share code, notes, and snippets.

@mmagm
Created August 1, 2013 15:52
Show Gist options
  • Save mmagm/6132656 to your computer and use it in GitHub Desktop.
Save mmagm/6132656 to your computer and use it in GitHub Desktop.
class Node
attr_accessor :next
attr_accessor :value
def initialize(value)
@next = nil
@value = value
end
end
class List
def initialize
@head = nil
@last = nil
end
def add(element)
node = Node.new(element)
if @head.nil?
@head = node
@last = node
else
@last.next = node
@last = node
end
end
def enum
enumerator = Enumerator.new do |e|
node = @head
until node.nil?
e << node.value
node = node.next
end
end
enumerator
end
def inspect
enum.to_a.inspect
end
def reverse!
return if @head.nil?
head = @last
while @head != head
element = @head
@head = @head.next
second = head.next
head.next = element
element.next = second
end
end
end
# a,b,c,d,e ; head = e ; head.next = nil, @head = a
# b,c,d,e,a ; head = e ; head.next = a, a.next = nil, @head = b
# c,d,e,b,a ; head = e ; head.next = b, b.next = a, @head = c
# d,e,c,b,a ; head = e ; head.next = c, c.next = b, @head = d
# e,d,c,b,a ; head = e ; head.next = d, d.next = c ; @head = e, @head == head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment