9
9
namespace App \Chapter03 ;
10
10
11
11
12
- class LinkedList
12
+ class LinkedList implements \Iterator
13
13
{
14
14
private $ _firstNode = NULL ;
15
15
private $ _totalNodes = 0 ;
16
+ private $ _currentNode = NULL ;
17
+ private $ _currentPosition = 0 ;
16
18
17
19
public function insert (string $ data = NULL )
18
20
{
@@ -268,4 +270,61 @@ public function getItemByPosition(int $position = 0)
268
270
269
271
}
270
272
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
+ }
271
330
}
0 commit comments