Got a question about PHP's SplDoublyLinkedList. If the nature of doubly linked lists is that every node has a reference to nodes on both left and right, why doesn't SplDoublyLinkedList offer methods to retrieve those neighbouring nodes based on current node?
$q = new SplDoublyLinkedList;
$q->push('A');
$q->push('B');
$q->push('C');
for ($q->rewind(); $q->valid(); $q->next()) {
$current = $q->current();
// $prev = $q->prev();
// $next = $q->next();
}
In the example above prev()
and next()
move iteration cursor. Is there a way of knowing what precedes and follows $current
without resorting to $q->key()
and $q->offsetGet($pos)
?
Thanks!
Keep track of prev and next values yourself, easier if you modify that for loop to use a while loop instead:
$prev = null;
$q->rewind();
while ($q->valid()) {
$current = $q->current();
echo 'PREV: ', $prev, PHP_EOL;
echo 'CURRENT: ', $current, PHP_EOL;
$prev = $current;
$q->next();
$next = $q->current();
echo 'NEXT: ', $next, PHP_EOL;
echo PHP_EOL;
}