Skip to content

Instantly share code, notes, and snippets.

@titanium-cranium
Created November 14, 2017 21:17
Show Gist options
  • Save titanium-cranium/a3beb16a0328f2a39b2f4f099ec6b39a to your computer and use it in GitHub Desktop.
Save titanium-cranium/a3beb16a0328f2a39b2f4f099ec6b39a to your computer and use it in GitHub Desktop.
Reverse a linked list with mutation
# This linked list reversal does not involve a stack, it simply
#creates a new set of nodes that point the opposite direction.
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
def reverse_list(node, previous=nil)
return if node.nil?
@head = LinkedListNode.new(node.value, previous)
reverse_list(node.next_node, @head)
return @head
end
def print_values(node)
print "#{node.value} --> "
if node.next_node.nil?
print "nil\n"
return
else
print_values(node.next_node)
end
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
print_values(node3)
puts "---------"
revlist = reverse_list(node3)
print_values(revlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment