Skip to content

Instantly share code, notes, and snippets.

View farithanasreen's full-sized avatar

farithanasreen

View GitHub Profile
class Node
attr_accessor :value, :next
def initialize(value, next_node)
@value = value
@next = next_node
end
end
class LinkedList
class Node
attr_accessor :value, :next
def initialize(value, next_node)
@value = value
@next = next_node
end
end
def initialize(value)
def insert(value)
@head = Node.new(value, nil) || return if @head.nil?
current = @head
# Traverse to the end of the list from the head node
while current.next
current = current.next
end
# Initialize a new node and append to the current last node
current.next = Node.new(value, nil)
end
def delete(value)
(puts "List is Empty") || return if @head.nil?
current = @head
if current.value.eql?(value)
# If first node is the deletion value assign head to next node
@head = current&.next
else
while current.next && (current.next.value != value)
current = current.next
end
def search(value)
(puts "List is Empty") || return if @head.nil?
current = @head
while current.next
(element_found = true) && break if current.value.eql?(value)
current = current.next
end
# Check if searched value is already found or is the last element
(element_found || current.value.eql?(value)) ? (puts "Element found") : (puts "Element not present")
end
def print_list
(puts "List is Empty") || return if @head.nil?
current = @head
while current.next
print "#{current.value} ->"
current = current.next
end
print "#{current.value}"
end
class LinkedList
class Node
attr_accessor :value, :next
def initialize(value, next_node)
@value = value
@next = next_node
end
end