Skip to content

Instantly share code, notes, and snippets.

@fogonthedowns
Last active May 1, 2017 00:04
Show Gist options
  • Select an option

  • Save fogonthedowns/fdacca42531f8623fc204516055a32d2 to your computer and use it in GitHub Desktop.

Select an option

Save fogonthedowns/fdacca42531f8623fc204516055a32d2 to your computer and use it in GitHub Desktop.
Linked List
class Node
attr_accessor :next, :value
def initialize(value)
@value = value
end
end
class LinkedList
attr_accessor :tail, :head
def initialize(head)
@head = head
@tail = head
end
def push(node)
@tail.next = node
@tail = node
end
def each(&block)
next_node = @head
until (next_node == nil) do
block.call(next_node)
next_node = next_node.next
end
end
def reverse_list!(curr=@head)
return curr if curr == nil or curr.next == nil
next_node = curr.next
new_head = reverse_list!(curr.next)
next_node.next = curr
curr.next = nil
self.head = new_head
return new_head
end
end
head = Node.new(0)
linked_list = LinkedList.new(head)
(1..5).each {|value| linked_list.push(Node.new(value)) }
linked_list.each{|x|p x.value unless x == nil}
linked_list.reverse_list!()
linked_list.each{|x|p x.value unless x == nil}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment