Class: LinkedList::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/linked_lists/linked_list/node.rb

Overview

Represents a node of a singly linked list.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = nil, next_node = nil) ⇒ Node

Returns a new instance of Node.

Parameters:

  • value (Object) (defaults to: nil)
  • next_node (self, nil) (defaults to: nil)


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

#nextself?

Returns Next node of the linked list.

Returns:

  • (self, nil)

    Next node of the linked list.



19
20
21
# File 'lib/linked_lists/linked_list/node.rb', line 19

def next
  @next
end

#valueObject

Returns The value stored by this node.

Returns:

  • (Object)

    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: []

Parameters:

  • value (Object)

    Value to be wrapped in a node.

Returns:

  • (self)


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`.

Parameters:

  • objects (Object)

Returns:

  • (self)


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

#inspectString

Returns:

  • (String)


31
32
33
# File 'lib/linked_lists/linked_list/node.rb', line 31

def inspect
  "#<#{self.class} #{value.inspect}>"
end

#to_listLinkedList

Set this node as the head of a new linked list.

Returns:



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