Last active
September 19, 2015 21:17
-
-
Save bstolte/37c8766932aba5e5fadd to your computer and use it in GitHub Desktop.
Reversed Link List #1
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 | |
class Stack | |
attr_reader :data | |
def initialize | |
@data = nil | |
end | |
# Push a value onto the stack | |
def push(value) | |
@data = LinkedListNode.new(value, @data) | |
end | |
# Pop an item off the stack. | |
# Remove the last item that was pushed onto the | |
# stack and return the value to the user | |
def pop | |
node = @data.value | |
@data = @data.next_node | |
return node | |
end | |
end | |
def reverse_list(list) | |
start_list = Stack.new.push(list) | |
print_values(list.value) | |
while list | |
reversed_list = list.pop | |
list = list.next_node | |
return reverse_list | |
end | |
return reverse_list | |
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