find the last node in a linked list in ruby

To find the last node in a linked list in Ruby, you can traverse the list until you reach the end. Here's an example implementation:

main.rb
class Node
  attr_accessor :value, :next_node
  
  def initialize(value, next_node = nil)
    @value = value
    @next_node = next_node
  end
end

class LinkedList
  attr_accessor :head
  
  def initialize
    @head = nil
  end
  
  def append(value)
    if @head.nil?
      @head = Node.new(value)
    else
      current = @head
      while current.next_node != nil
        current = current.next_node
      end
      current.next_node = Node.new(value)
    end
  end
  
  def last_node
    return nil if @head.nil?

    current = @head
    while current.next_node != nil
      current = current.next_node
    end
    current
  end
end
637 chars
39 lines

In this implementation, we define a Node class to represent each node in the linked list, with a value attribute and a next_node attribute that points to the next node in the list. We also define a LinkedList class with an append method to add nodes to the end of the list, and a last_node method that traverses the list to find the last node.

To use this implementation, you would create a new LinkedList, append some nodes to it, and then call the last_node method to find the last node:

main.rb
list = LinkedList.new
list.append(1)
list.append(2)
list.append(3)
last_node = list.last_node
puts last_node.value # prints 3
126 chars
7 lines

related categories

gistlibby LogSnag