remove a node from the end of a linked list in ruby

To remove the last node of a singly linked list in Ruby, you can use the following code:

main.rb
class Node
  attr_accessor :value, :next_node

  def initialize(value)
    @value = value
  end
end

class LinkedList
  def initialize
    @head = nil
  end

  def add(value)
    if @head.nil?
      @head = Node.new(value)
    else
      current_node = @head
      while current_node.next_node != nil
        current_node = current_node.next_node
      end
      current_node.next_node = Node.new(value)
    end
  end

  def remove_last
    current_node = @head
    previous_node = nil
    if current_node.nil?
      return
    end
    if current_node.next_node.nil?
      @head = nil
      return
    end
    while current_node.next_node != nil
      previous_node = current_node
      current_node = current_node.next_node
    end
    previous_node.next_node = nil
  end
end
777 chars
43 lines

You can then create a linked list and call the remove_last method to remove the last node from the end of the list:

main.rb
list = LinkedList.new
list.add("apple")
list.add("banana")
list.add("cherry")
list.remove_last
# The list now contains "apple" and "banana"
140 chars
7 lines

gistlibby LogSnag