Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to reverse a singly linked list in-place in Ruby

1 Answer

0 votes
# Node class for a singly linked list
class ListNode
  attr_accessor :value, :next

  def initialize(value)
    @value = value      # data stored in the node
    @next = nil         # reference to the next node
  end
end

# Reverse the linked list in-place
def reverse_list(head)
  prev = nil            # will become the new head
  current = head        # pointer to traverse the list

  while current
    next_node = current.next   # save next node
    current.next = prev        # reverse the link
    prev = current             # move prev forward
    current = next_node        # move current forward
  end

  prev  # prev is the new head
end

# Print the linked list
def print_list(head)
  temp = head
  while temp
    print temp.value
    print " -> " if temp.next
    temp = temp.next
  end
  puts
end

# Build a sample list: 1 -> 2 -> 3 -> 4 -> 5
head = ListNode.new(1)
head.next = ListNode.new(2)
head.next.next = ListNode.new(3)
head.next.next.next = ListNode.new(4)
head.next.next.next.next = ListNode.new(5)

puts "Original list:"
print_list(head)

# Reverse the list
head = reverse_list(head)

puts "Reversed list:"
print_list(head)


=begin
run:
 
Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1
 
=end

 



answered Jun 30 by avibootz
...