Making the linked list iterable

So far, we have seen that we can traverse each node of the linked list using a while loop inside the methods. What if we need to iterate from outside using just the linked list object? It is very much possible to achieve this. PHP has a very intuitive iterator interface that allows any external iterators to iterate through an object internally. The Iterator interface provides the following methods:

  • Current: Return the current element
  • Next: Move forward to the next element
  • Key: Return the key of the current element
  • Rewind: Rewind the Iterator to the first element
  • Valid: Checks whether the current position is valid

We will now implement these methods in our LinkedList class to make our object iterate through the nodes from the object directly. In order to track the current node and the current position within the list during iteration, we will require two new properties for our LinkedList class:

private $_currentNode = NULL; 
private $_currentPosition = 0;

The $_currentNode property will track the current node during the iteration, and $_currentPosition will track the current position during the iteration. We also need to make sure that our class LinkedList class is also implementing the Iterator interface. It will look like this:

class LinkedList implements Iterator{ 

}

Now, let's implement those five new methods to make our linked list object iterable. These five methods are very straightforward and simple to implement. Here is the code for that:

    public function current() { 
return $this->_currentNode->data;
}

public function next() {
$this->_currentPosition++;
$this->_currentNode = $this->_currentNode->next;
}

public function key() {
return $this->_currentPosition;
}

public function rewind() {
$this->_currentPosition = 0;
$this->_currentNode = $this->_firstNode;
}

public function valid() {
return $this->_currentNode !== NULL;
}

Now, we have a list that is iterable. This means that now we can iterate through our linked list object using the foreach loop or any other iteration process we wish to follow. So, now, if we write the following code, we will see all the book titles:

foreach ($BookTitles as $title) { 
echo $title . " ";
}

Another approach can be using the rewind, valid, next, and current methods from the iterable interface. It will have the same output as the preceding code:

for ($BookTitles->rewind(); $BookTitles->valid(); 
$BookTitles->next()) {
echo $BookTitles->current() . " ";
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset