Last active
June 21, 2018 03:26
-
-
Save Brandongoodman615/558adaed4dc17de86ab0f14f010c08d9 to your computer and use it in GitHub Desktop.
Brandon Linked_List Solution
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 print_values(list_node) | |
print "#{list_node.value} --> " | |
if list_node.next_node.nil? | |
print "nil\n" | |
return | |
else | |
print_values(list_node.next_node) | |
end | |
end | |
# list = node3 / node2 / node1 | |
def reverse_list(list, previous=nil) # / <-represents each recursion when reverse_list is called inside method | |
new_head = list.next_node # new_head = node2 / new_head = node1 / new_head = nil | |
list.next_node = previous # node3.next_node = nil / node2.next_node = node3. / node1.next_node = node2 | |
if new_head # != nil | |
reverse_list(new_head, list) # reverse_list(node2, node3) / reverse_list(node1, node2) / return list if new_head is nil | |
else # ^ = node1 | |
list | |
end | |
end | |
def check_if_loop(node) | |
t = node | |
h = node | |
while h != nil | |
h = h.next_node | |
return false if h == nil | |
h = h.next_node | |
t = t.next_node | |
return true if h == t | |
end | |
end | |
node1 = LinkedListNode.new(37) # node2 | |
node2 = LinkedListNode.new(99, node1) # node3 | |
node3 = LinkedListNode.new(12, node2) # nil | |
# node1.next_node = node3 # <- Makes infinite loop | |
# puts check_if_loop(node3) # <- return true or false for infinite loop | |
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