Skip to content

Instantly share code, notes, and snippets.

@dronov
Last active March 27, 2018 17:37
Show Gist options
  • Save dronov/762f77fa783e22ae47240648c542f705 to your computer and use it in GitHub Desktop.
Save dronov/762f77fa783e22ae47240648c542f705 to your computer and use it in GitHub Desktop.
class Element
attr_accessor :value, :next_value
def initialize(value, next_value)
@value = value
@next_value = next_value
end
end
class SingleLinkedList
def initialize(value)
@head = Element.new(value, nil)
end
def add(value)
current = @head
while current.next_value != nil
current = current.next_value
end
current.next_value = Element.new(value, nil)
end
def delete(value)
current.next_value = @head
if current.value = value
@head = current.next_value
else
while (current.next_value != nil) && (current.next_value.value != value)
current = current.next_value
end
unless current.next_value == nil
current.next_value = current.next_value.next_value
end
end
end
def return_list
elements = []
current = @head
while current.next_value != nil
elements << current
current = current.next_value
end
elements << current
end
def length
count = 0
current = @head
if current != nil
while current.next_value != nil
count+=1
current = current.next_value;
end
else
return 0
end
count
end
end
list = SingleLinkedList.new(1)
list.add(2)
list.add(3)
list.add(4)
list.add(5)
list.add(100)
p list.return_list
p list.length
p list.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment