Last active
September 12, 2016 02:51
-
-
Save danielpowell4/f8bbe97cf8e0757a13db007fb3ebcb00 to your computer and use it in GitHub Desktop.
Linked List Exercise in Ruby. Handles infinite lists via Floyd Cycle Detection as well as reversing list with and without mutation.
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_list(list_node) | |
print "#{list_node.value} --> " | |
if infinite_list?(list_node)[0] | |
infinite_list?(list_node)[1].times do | |
list_node = list_node.next_node | |
print "#{list_node.value} --> " | |
end | |
print "and then starts repeating\n" | |
else | |
if list_node.next_node.nil? | |
print "nil\n" | |
return | |
else | |
print_list(list_node.next_node) | |
end | |
end | |
end | |
class Stack | |
attr_reader :data | |
def initialize | |
@data = nil | |
end | |
def push(value) | |
@data = LinkedListNode.new(value, @data) | |
end | |
end | |
def reverse_list_via_stack(list_item) | |
stack = Stack.new | |
while list_item | |
stack.push(list_item.value) | |
list_item = list_item.next_node | |
end | |
stack.data | |
end | |
def reverse_list_via_mutatation(list_item, previous = nil) | |
og_next = list_item.next_node | |
list_item.next_node = previous | |
og_next ? reverse_mutated_list(og_next, list_item) : list_item | |
end | |
def infinite_list?(list_item) | |
count = 0 | |
turtle = list_item | |
hair = list_item.next_node | |
if (turtle == nil || hair == nil) | |
return false, count | |
end | |
while hair != turtle | |
count += 1 | |
if hair.value == nil | |
return false, count | |
end | |
hair = hair.next_node.next_node | |
turtle = turtle.next_node | |
end | |
return true, count | |
rescue NoMethodError | |
[false, count] | |
end | |
# --- setup | |
# - standard | |
node1 = LinkedListNode.new(37) | |
node2 = LinkedListNode.new(99, node1) | |
node3 = LinkedListNode.new(12, node2) | |
# - looped | |
loop_node1 = LinkedListNode.new(6) | |
loop_node2 = LinkedListNode.new(5, loop_node1) | |
loop_node3 = LinkedListNode.new(4, loop_node2) | |
loop_node4 = LinkedListNode.new(3, loop_node3) | |
loop_node5 = LinkedListNode.new(2, loop_node4) | |
loop_node6 = LinkedListNode.new(1, loop_node5) | |
loop_node1.next_node = loop_node6 | |
# --- output | |
print "\nHandling standard list:\n" | |
print_list(node3) | |
print "\nReverse: no mutation):\n" | |
print_list(reverse_list_via_stack(node3)) | |
print "\nReverse: with mutation):\n" | |
print_list(reverse_list_via_mutatation(node3)) | |
print "\nHandling looped list:\n" | |
print_list(loop_node6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment