Class: CircularLinked::List
- Inherits:
-
Object
- Object
- CircularLinked::List
- Defined in:
- lib/circular_linked/list.rb
Instance Attribute Summary collapse
-
#head ⇒ Object
Returns the value of attribute head.
Instance Method Summary collapse
- #add(value) ⇒ Object
- #each ⇒ Object
- #find(value) ⇒ Object
-
#initialize(*values) ⇒ List
constructor
A new instance of List.
- #items_value ⇒ Object
- #last_node ⇒ Object
- #length ⇒ Object
- #remove(value) ⇒ Object
Constructor Details
Instance Attribute Details
#head ⇒ Object
Returns the value of attribute head.
4 5 6 |
# File 'lib/circular_linked/list.rb', line 4 def head @head end |
Instance Method Details
#add(value) ⇒ Object
12 13 14 15 16 17 18 19 |
# File 'lib/circular_linked/list.rb', line 12 def add(value) new_node = Node.new(value, head) @head ||= new_node new_node.next ||= head last_node.next = new_node end |
#each ⇒ Object
73 74 75 76 77 78 79 80 81 82 |
# File 'lib/circular_linked/list.rb', line 73 def each return unless head node = head loop do yield(node) node = node.next break if node == head end end |
#find(value) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/circular_linked/list.rb', line 29 def find(value) return nil unless head node = head while node.value != value node = node.next return nil if node == head end node end |
#items_value ⇒ Object
57 58 59 60 61 62 63 |
# File 'lib/circular_linked/list.rb', line 57 def items_value values = [] return values unless head each {|node| values.push(node.value) } values end |
#last_node ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/circular_linked/list.rb', line 21 def last_node return nil unless head node = head node = node.next while node.next != head node end |
#length ⇒ Object
65 66 67 68 69 70 71 |
# File 'lib/circular_linked/list.rb', line 65 def length length = 0 return length unless head each { length += 1 } length end |
#remove(value) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/circular_linked/list.rb', line 41 def remove(value) node = find(value) return unless node if head.next == head @head = nil return end node_before = head node_before = node_before.next while node_before.next != node node_before.next = node.next @head = node.next if node == head end |