Created
August 27, 2016 20:46
-
-
Save ashlynnpai/28fbfdf02ac87bebe695d6773360f95a 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 | |
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 | |
def reverse_list(list) | |
# ADD CODE HERE | |
my_stack = Stack.new | |
while list | |
# ADD CODE HERE | |
my_stack.push(list.value) | |
list = list.next_node | |
end | |
# ADD CODE HERE | |
my_stack | |
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) | |
@data.print_values(@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 | |
top_value = @data.value | |
@data = @data.next_node | |
top_value | |
end | |
end | |
# stack = Stack.new | |
# stack.push(1) | |
# stack.push(2) | |
# stack.push(3) | |
# puts stack.pop | |
# puts stack.pop | |
# puts stack.pop | |
node1 = LinkedListNode.new(37) | |
node2 = LinkedListNode.new(99, node1) | |
node3 = LinkedListNode.new(12, node2) | |
node3.print_values(node3) | |
node3.reverse_list(node3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment