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

To remove a node from the middle of a linked list in Ruby, we need to perform the following steps:

  1. Traverse the linked list and find the node that we want to remove.
  2. Update the next pointer of the previous node to point to the next node of the node we want to remove.
  3. Remove the node from memory by setting its value to nil.

Assuming we have a linked list class with a head attribute that points to the first node of the list, the code to remove a node with a given value from the middle of the list would look like this:

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 remove_node(value)
    current_node = @head
    previous_node = nil

    while current_node != nil 
      if current_node.value == value
        if previous_node != nil
          previous_node.next_node = current_node.next_node
        else
          @head = current_node.next_node
        end

        current_node.value = nil
        return
      end

      previous_node = current_node
      current_node = current_node.next_node
    end

    puts "Node with value #{value} not found in list"
  end
end
697 chars
36 lines

Here, we traverse the linked list until we find a node with the given value. Then, we update the next pointer of the previous node to point to the next node of the current node. If the current node is the first node of the list, we update the head attribute of the list. Finally, we remove the current node from memory by setting its value to nil. This approach has a time complexity of O(n) and a space complexity of O(1).

related categories

gistlibby LogSnag