Last active
October 2, 2015 01:41
-
-
Save ianhirschfeld/b40dded1e449bbf3aa6a 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
class LinkedListNode | |
attr_accessor :value, :next_node | |
def initialize(value, next_node=nil) | |
@value = value | |
@next_node = next_node | |
end | |
end | |
def reverse_list(list, previous=nil) | |
# Base Case: We have reached the last node of the original list. | |
# This is when we take that last node and point it to the previous node. | |
# Then we return the list (which will now be reversed). | |
if list.next_node.nil? | |
list.next_node = previous | |
return list | |
# Other Case: We aren't yet at the end so let's keep reversing. | |
# To keep reversing, we assign the current node value into previous, | |
# and we reverse the rest of the list. | |
# | |
# NOTE: If we don't create a new previous node with an empty next_node and | |
# instead just pass list as previous, we will get an infinite loop. | |
else | |
# return reverse_list(list.next_node, list) # <--- Infinite loop | |
previous = LinkedListNode.new(list.value) | |
return reverse_list(list.next_node, previous) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment