Class: DataTypes::LinkedList
- Inherits:
-
Object
- Object
- DataTypes::LinkedList
- Includes:
- Enumerable
- Defined in:
- lib/data_types/linked_list/linked_list.rb
Instance Method Summary collapse
-
#append(value) ⇒ Object
Append to the end of the list.
-
#display ⇒ Object
Print the list elements.
-
#each ⇒ Object
Implement the ‘each` method to make LinkedList Enumerable.
-
#empty? ⇒ Boolean
Check if the list is empty.
-
#find(value) ⇒ Object
Find an element by value.
-
#initialize ⇒ LinkedList
constructor
A new instance of LinkedList.
-
#prepend(value) ⇒ Object
Insert a new element at the beginning.
-
#size ⇒ Object
Get size of the linked list.
-
#to_a ⇒ Object
Convert linked list to an array.
Constructor Details
#initialize ⇒ LinkedList
Returns a new instance of LinkedList.
8 9 10 11 |
# File 'lib/data_types/linked_list/linked_list.rb', line 8 def initialize @head = nil @tail = nil end |
Instance Method Details
#append(value) ⇒ Object
Append to the end of the list
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/data_types/linked_list/linked_list.rb', line 14 def append(value) new_node = Node.new(value) if @head.nil? @head = new_node @tail = new_node else @tail.next = new_node @tail = new_node end end |
#display ⇒ Object
Print the list elements
73 74 75 |
# File 'lib/data_types/linked_list/linked_list.rb', line 73 def display each { |value| puts value } end |
#each ⇒ Object
Implement the ‘each` method to make LinkedList Enumerable
49 50 51 52 53 54 55 |
# File 'lib/data_types/linked_list/linked_list.rb', line 49 def each current = @head while current yield current.value current = current.next end end |
#empty? ⇒ Boolean
Check if the list is empty
63 64 65 |
# File 'lib/data_types/linked_list/linked_list.rb', line 63 def empty? @head.nil? end |
#find(value) ⇒ Object
Find an element by value
39 40 41 42 43 44 45 46 |
# File 'lib/data_types/linked_list/linked_list.rb', line 39 def find(value) current = @head while current return current if current.value == value current = current.next end nil end |
#prepend(value) ⇒ Object
Insert a new element at the beginning
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/data_types/linked_list/linked_list.rb', line 27 def prepend(value) new_node = Node.new(value) if @head.nil? @head = new_node @tail = new_node else new_node.next = @head @head = new_node end end |
#size ⇒ Object
Get size of the linked list
68 69 70 |
# File 'lib/data_types/linked_list/linked_list.rb', line 68 def size count end |
#to_a ⇒ Object
Convert linked list to an array
58 59 60 |
# File 'lib/data_types/linked_list/linked_list.rb', line 58 def to_a map { |value| value } end |