SplDoublyLinkedList - how to fetch nodes surrounding current node

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;
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)?


1 answer

  • answered 2018-01-11 19:43 Mark Baker

    Keep track of prev and next values yourself, easier if you modify that for loop to use a while loop instead:

    $prev = null;
    while ($q->valid()) {
        $current = $q->current();
        echo 'PREV: ', $prev, PHP_EOL;
        echo 'CURRENT: ', $current, PHP_EOL;
        $prev = $current;
        $next = $q->current();
        echo 'NEXT: ', $next, PHP_EOL;
        echo PHP_EOL;