title: How to reverse a linked list in Ruby
body: <p>In the mutation example below, I don't understand how the linked list is reversed.</p>
  
  <pre><code>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} --&gt; "
    if list_node.next_node.nil?
      print "nil\n"
      return
    else
      print_values(list_node.next_node)
    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)
  </code></pre>
  
  <p>If I just return <code>current_head</code>, I get <code>99-&gt;37-&gt;nil</code>, which makes sense because <code>99</code> would be <code>next_node</code>. Returning the next line, </p>
  
  <pre><code>list.next_node = previous
  </code></pre>
  
  <p>throws an error because <code>print_values</code> method can't print the value for <code>nil</code>. I'm not understanding what is reversing the list. If anyone could explain this to me, I would appreciate it.</p>