Created
July 21, 2018 23:07
-
-
Save cefaijustin/32c1023de8176caa5d67e22ec4a1350c to your computer and use it in GitHub Desktop.
Ruby Linked List Two
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) | |
if list_node | |
print "#{list_node.value} --> " | |
print_values(list_node.next_node) | |
else | |
print "nil\n" | |
return | |
end | |
end | |
class Stack | |
attr_reader :data | |
def initialize | |
@data = nil | |
end | |
def push(value) | |
@data << (value) | |
end | |
def pop | |
value = @data.value | |
@data = @data.next_node | |
value | |
end | |
end | |
def reverse_list(list, previous=nil) | |
current_head = list.next_node | |
list.next_node = previous | |
if current_head | |
reverse_list(current_head, list) | |
else | |
list | |
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