I created a singly LinkedList class with ruby.
Everything went well till trying to reverse the linked list.
It does not reverse linkedlist by this method, but when I add
@head.next = nil
after left_tmp = @head in reverse method, it just works fine.
I couldn’t figure out why it works when I add that, does anyone have the explanation?
BTW I am fairly new to ruby, so please don’t hesitate to tell me if there are some other things that are not “Good Practice in Ruby“.
Here is classes and relevant methods:
class LlNode
attr_reader :data
attr_accessor :next
def initialize(val=nil)
@data = val
@next = nil
end
def to_s
"node_data=#{@data}"
end
end
class LinkedList
def initialize
@list = []
@head = LlNode.new
end
def insert(val)
n = LlNode.new val
# List is empty
if is_empty?
@head = n
else
n.next = @head
@head = n
end
self
end
def reverse
return if is_empty? or @head.next.nil?
curr = @head.next
right_tmp = curr.next
left_tmp = @head
while curr != nil
curr.next = left_tmp
left_tmp = curr
curr = right_tmp
right_tmp = right_tmp.next unless right_tmp.nil?
end
@head = left_tmp
end
end
When you’re reversing a
linked list, the first node becomes the last. In asingly-linked list, the last node’snextpointer points tonull.@head, which is initially your first node becomes the last. That’s why you add the@head.next = nil.Edit: Simulating a dry-run to better explain the problem
Assume two nodes in the linked list:
1->2First iteration of the
whileloop:There is no second iteration since
curr == nilNow:
Final linked list state is: