Class: Ds101::LinkedList::SingleLinkedList
- Inherits:
-
Object
- Object
- Ds101::LinkedList::SingleLinkedList
- Includes:
- Common
- Defined in:
- lib/ds_101/linked_list/single_linked_list.rb
Defined Under Namespace
Classes: Node
Instance Attribute Summary collapse
-
#head ⇒ Object
Returns the value of attribute head.
-
#length ⇒ Object
Returns the value of attribute length.
-
#tail ⇒ Object
Returns the value of attribute tail.
Class Method Summary collapse
Instance Method Summary collapse
- #append(value) ⇒ Object
-
#initialize ⇒ SingleLinkedList
constructor
A new instance of SingleLinkedList.
- #remove(value) ⇒ Object
- #remove_head ⇒ Object
Methods included from Common
#clear, #concat, #each, #find, #find_by, #to_a
Constructor Details
#initialize ⇒ SingleLinkedList
Returns a new instance of SingleLinkedList.
10 11 12 13 14 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 10 def initialize @head = nil @tail = nil @length = 0 end |
Instance Attribute Details
#head ⇒ Object
Returns the value of attribute head.
8 9 10 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 8 def head @head end |
#length ⇒ Object
Returns the value of attribute length.
8 9 10 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 8 def length @length end |
#tail ⇒ Object
Returns the value of attribute tail.
8 9 10 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 8 def tail @tail end |
Class Method Details
.init_from_arr(arr) ⇒ Object
16 17 18 19 20 21 22 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 16 def self.init_from_arr(arr) list = SingleLinkedList.new arr.each do |value| list.append(value) end list end |
Instance Method Details
#append(value) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 24 def append(value) node = Node.new(value: value) if head.nil? @head = node else tail.next = node end @tail = node @length += 1 node end |
#remove(value) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 36 def remove(value) return unless head return remove_head if head.value == value current = head current = current.next while current&.next && current.next.value != value return unless current&.next if current.next == tail @tail = current else current.next = current.next.next end @length -= 1 end |
#remove_head ⇒ Object
52 53 54 55 56 57 58 59 60 |
# File 'lib/ds_101/linked_list/single_linked_list.rb', line 52 def remove_head if head.next.nil? @head = nil @tail = nil else @head = head.next end @length -= 1 end |