Class: DataStructures101::LinkedList
- Inherits:
-
Object
- Object
- DataStructures101::LinkedList
- Includes:
- Enumerable
- Defined in:
- lib/data_structures_101/linked_list.rb
Overview
Defined Under Namespace
Classes: Node
Instance Attribute Summary collapse
- #size ⇒ Object readonly
Instance Method Summary collapse
- #<<(value) ⇒ Object
- #delete(value) ⇒ Object
- #each ⇒ Object
- #fetch(index) ⇒ Object
- #first(n = nil) ⇒ Object
-
#initialize(*values) ⇒ LinkedList
constructor
A new instance of LinkedList.
- #insert(index, *values) ⇒ Object
- #last(n = nil) ⇒ Object
- #push(*values) ⇒ Object
Constructor Details
#initialize(*values) ⇒ LinkedList
Returns a new instance of LinkedList.
30 31 32 33 34 35 36 37 |
# File 'lib/data_structures_101/linked_list.rb', line 30 def initialize(*values) @size = 0 @head = Node.new(nil) @tail = Node.new(nil, @head) @head.next = @tail push(*values) end |
Instance Attribute Details
#size ⇒ Object (readonly)
28 29 30 |
# File 'lib/data_structures_101/linked_list.rb', line 28 def size @size end |
Instance Method Details
#<<(value) ⇒ Object
39 40 41 |
# File 'lib/data_structures_101/linked_list.rb', line 39 def <<(value) push(value) end |
#delete(value) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/data_structures_101/linked_list.rb', line 43 def delete(value) curr = @head.next return_value = nil until curr == @tail if curr.value == value remove_node(curr) return_value = curr.value end curr = curr.next end return_value end |
#each ⇒ Object
57 58 59 60 61 62 63 64 65 |
# File 'lib/data_structures_101/linked_list.rb', line 57 def each return enum_for(:each) unless block_given? curr = head.next until curr.nil? yield curr.value curr = curr.next end end |
#fetch(index) ⇒ Object
67 68 69 |
# File 'lib/data_structures_101/linked_list.rb', line 67 def fetch(index) fetch_node(index).value end |
#first(n = nil) ⇒ Object
82 83 84 85 86 87 88 |
# File 'lib/data_structures_101/linked_list.rb', line 82 def first(n = nil) return @head.next.value if n.nil? raise ArgumentError, 'negative array size' if n.negative? new_list_from_range(0, n - 1) end |
#insert(index, *values) ⇒ Object
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/data_structures_101/linked_list.rb', line 71 def insert(index, *values) curr = fetch_node(index) curr = index.negative? ? curr : curr.prev values.each do |value| curr = add_node(value, curr.next) end self end |
#last(n = nil) ⇒ Object
90 91 92 93 94 95 96 |
# File 'lib/data_structures_101/linked_list.rb', line 90 def last(n = nil) return @tail.prev.value if n.nil? raise ArgumentError, 'negative array size' if n.negative? new_list_from_range(size - n, size - 1) end |
#push(*values) ⇒ Object
98 99 100 101 102 103 |
# File 'lib/data_structures_101/linked_list.rb', line 98 def push(*values) values.each do |value| add_node(value, @tail) end self # Allows to concatenate consecutive calls to push end |