Class: Algorithmix::DataStructure::Generic::LinkedList::Iterator

Inherits:
Object
  • Object
show all
Defined in:
lib/algorithmix/data_structure/generic/linked_list.rb

Overview

Iterator class which gives couple of useful methods, for moving through the elements of a given list.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ Iterator

Returns a new instance of Iterator.

Raises:

  • (ArgumentError)


388
389
390
391
392
393
394
395
396
# File 'lib/algorithmix/data_structure/generic/linked_list.rb', line 388

def initialize(node)
  raise ArgumentError, "Invalid argument" unless node.is_a?(Node) || node.is_a?(LinkedList)

  @begin = @node.is_a?(Node) ? node : node.front
  @current = @node.is_a?(Node) ? node : node.front
  @next_node = @node.is_a?(Node) ? node : node.front

  @next_node = @next_node.next_node
end

Instance Attribute Details

#currentObject (readonly)

Returns the value of attribute current.



386
387
388
# File 'lib/algorithmix/data_structure/generic/linked_list.rb', line 386

def current
  @current
end

#next_nodeObject (readonly)

Returns the value of attribute next_node.



386
387
388
# File 'lib/algorithmix/data_structure/generic/linked_list.rb', line 386

def next_node
  @next_node
end

Instance Method Details

#beginObject

Resets the current state of the iterator. All iterators will point to the front of the list.



400
401
402
# File 'lib/algorithmix/data_structure/generic/linked_list.rb', line 400

def begin
  @current = @next_node = @begin
end

#nextObject

Moves the iterator to the next position, and sets the current iterator to the previous position of the next node.

Raises:



406
407
408
409
410
411
# File 'lib/algorithmix/data_structure/generic/linked_list.rb', line 406

def next
  raise OutOfBound, "No more elements." if @next_node.nil?
  @current = @next_node
  @next_node = @next_node.next_node
  self
end

#valueObject

Returns the value at the current node.



414
415
416
# File 'lib/algorithmix/data_structure/generic/linked_list.rb', line 414

def value
  @current.value
end