Class: LinkedList::Node
- Inherits:
-
Object
- Object
- LinkedList::Node
- Defined in:
- lib/linked_lists/linked_list/node.rb
Overview
Represents a node of a singly linked list.
Instance Attribute Summary collapse
-
#next ⇒ self?
Next node of the linked list.
-
#value ⇒ Object
The value stored by this node.
Class Method Summary collapse
- .wrap(value) ⇒ self (also: [])
Instance Method Summary collapse
-
#initialize(value = nil, next_node = nil) ⇒ Node
constructor
A new instance of Node.
-
#insert_after(*objects) ⇒ self
Inserts the given ‘objects` after `self`.
- #inspect ⇒ String
-
#to_list ⇒ LinkedList
Set this node as the head of a new linked list.
Constructor Details
#initialize(value = nil, next_node = nil) ⇒ Node
Returns a new instance of Node.
25 26 27 28 |
# File 'lib/linked_lists/linked_list/node.rb', line 25 def initialize(value = nil, next_node = nil) @value = value @next = next_node end |
Instance Attribute Details
#next ⇒ self?
Returns Next node of the linked list.
19 20 21 |
# File 'lib/linked_lists/linked_list/node.rb', line 19 def next @next end |
#value ⇒ Object
Returns The value stored by this node.
21 22 23 |
# File 'lib/linked_lists/linked_list/node.rb', line 21 def value @value end |
Class Method Details
.wrap(value) ⇒ self Also known as: []
9 10 11 12 13 |
# File 'lib/linked_lists/linked_list/node.rb', line 9 def wrap(value) return value if value.is_a?(self) new(value) end |
Instance Method Details
#insert_after(*objects) ⇒ self
Inserts the given ‘objects` after `self`.
Time complexity is *O(m)* where m is the length of given ‘objects`.
41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/linked_lists/linked_list/node.rb', line 41 def insert_after(*objects) prev_node = self objects.each do |obj| new_node = self.class.new obj new_node.next = prev_node.next prev_node.next = new_node prev_node = new_node end self end |
#inspect ⇒ String
31 32 33 |
# File 'lib/linked_lists/linked_list/node.rb', line 31 def inspect "#<#{self.class} #{value.inspect}>" end |
#to_list ⇒ LinkedList
Set this node as the head of a new linked list.
57 58 59 60 61 |
# File 'lib/linked_lists/linked_list/node.rb', line 57 def to_list list = LinkedList.new list.head = self list end |