I am implementing a reversed linked list using a stack.
Class Stack has methods push and pop, which turn a linked list into a stack from which the last element can be extracted in order to reverse the order.
I've encountered a similar situation here, and I'm trying to add a method to that base case. I'm trying to implement a reverse_list method that makes use of the Stack class's push and pop in order to change the pointer and reverse the linked list.
This is what I tried:
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 = LinkedListNode.new(value, @data)
end
def pop
return nil if @data.nil?
returning_value = @data.value
@data = @data.next_element
returning_value
end
end
def reverse_list(list)
stack = Stack.new.push(list.value)
list = list.next_node
while list
stack.push(list.value)
list = list.next_node
end
stack.pop
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
revlist = reverse_list(node3)
print_values(revlist)
# should return 37 --> 99 --> 12 --> nil
I get errors when calling the Stack class in the reverse_list method (undefined method push for <Context::LinkedListNode:0x00000001c5e0a8>).
I'm at a loss as to why I cannot use Stack, push, and pop inside reverse_list. Any tips as to how I could go about implementing reverse_list will be well received.