Skip to content

Commit 7287794

Browse files
committed
Made LinkedList traversable via Iterator interface
1 parent c776845 commit 7287794

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

chap-03/linked-lists.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,10 @@
7272
// Retrieve the 2nd item from the list
7373
echo $bookTitles->getItemByPosition(2)->data;
7474
echo SEPERATOR;
75+
76+
// We've made the list Iterable, reverse list again and loop through it.
77+
$bookTitles->reverse();
78+
foreach ($bookTitles as $title){
79+
echo $title . PHP_EOL;
80+
}
81+

src/Chapter03/LinkedList.php

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@
99
namespace App\Chapter03;
1010

1111

12-
class LinkedList
12+
class LinkedList implements \Iterator
1313
{
1414
private $_firstNode = NULL;
1515
private $_totalNodes = 0;
16+
private $_currentNode = NULL;
17+
private $_currentPosition = 0;
1618

1719
public function insert(string $data = NULL)
1820
{
@@ -268,4 +270,61 @@ public function getItemByPosition(int $position = 0)
268270

269271
}
270272

273+
/**
274+
* Return the current element
275+
* @link https://php.net/manual/en/iterator.current.php
276+
* @return mixed Can return any type.
277+
* @since 5.0.0
278+
*/
279+
public function current()
280+
{
281+
return $this->_currentNode->data;
282+
}
283+
284+
/**
285+
* Move forward to next element
286+
* @link https://php.net/manual/en/iterator.next.php
287+
* @return void Any returned value is ignored.
288+
* @since 5.0.0
289+
*/
290+
public function next()
291+
{
292+
$this->_currentPosition++;
293+
$this->_currentNode = $this->_currentNode->next;
294+
}
295+
296+
/**
297+
* Return the key of the current element
298+
* @link https://php.net/manual/en/iterator.key.php
299+
* @return mixed scalar on success, or null on failure.
300+
* @since 5.0.0
301+
*/
302+
public function key()
303+
{
304+
return $this->_currentPosition;
305+
}
306+
307+
/**
308+
* Checks if current position is valid
309+
* @link https://php.net/manual/en/iterator.valid.php
310+
* @return boolean The return value will be casted to boolean and then evaluated.
311+
* Returns true on success or false on failure.
312+
* @since 5.0.0
313+
*/
314+
public function valid()
315+
{
316+
return $this->_currentNode !== NULL;
317+
}
318+
319+
/**
320+
* Rewind the Iterator to the first element
321+
* @link https://php.net/manual/en/iterator.rewind.php
322+
* @return void Any returned value is ignored.
323+
* @since 5.0.0
324+
*/
325+
public function rewind()
326+
{
327+
$this->_currentPosition = 0;
328+
$this->_currentNode = $this->_firstNode;
329+
}
271330
}

0 commit comments

Comments
 (0)