如何使用 SplDoublyLinkedList 模拟这个双向链表动画?

How to mimic this doubly linked list animation using SplDoublyLinkedList?

我试图对使用此 tool:

生成的双向链表动画进行逆向工程

所以我试过了:

<?php

$dll = new \SplDoublyLinkedList();

$dll->unshift(200);//inserir no início
$dll->unshift(100);//inserir no início
$dll->push(34);//inserir no final
$dll->push(35);//inserir no final
$dll->add(2, 3); //inserir em posicao específica
$dll->unshift(670);//inserir no início
$dll->add(($dll->count() / 2)-1, 450);//inserir no meio
$dll->pop(); //remover do final
$dll->shift(); //remover do início
$dll->offsetUnset(1);//remover de posicao específica

$prev = null;
$dll->rewind(); //rebobinando
while ($dll->valid()) {
    $current = $dll->current();
    echo 'Atual: '.$current, "\n";
    $dll->next();
}

但是结果和动画不一样:( 如何模仿这个双向链表动画并得到相同的结果?

我认为您不能仅使用 PHP 来模仿该动画,至少这并不容易。您可以通过在每一步打印列表内容并使用 sleep 观察正在输出的更改来以某种方式动画化列表内容的输出:

<?php

$dll = new \SplDoublyLinkedList();

// add 200 to the list using push. Unshift has the same effect because the list is empty
$dll->push(200);
output($dll);

// insert 100 at the beginning of the list
$dll->unshift(100); 
output($dll);

// add 34 the end of the list
$dll->push(34); 
output($dll);

// add 35 the end of the list
$dll->push(35);
output($dll);

// insert 3 on the second position (usually a loop to find the index would be necessary)
$dll->add(2, 3);
output($dll);

// insert 670 at the beginning of the list
$dll->unshift(670);
output($dll);

// add 450 on the third position 
$dll->add(3, 450);
output($dll);

// remove last element of the list
$dll->pop();
output($dll);

// remove first element of the list
$dll->shift();
output($dll);

// remove from position 1 (second linked list element)
$dll->offsetUnset(1); 
output($dll);

function output(&$dll) {
    ob_start();

    $dll->rewind();

    $values = [];
    while ($dll->valid()) {
        $values[] = $dll->current();
        $dll->next();
    }

    echo "[ " . implode(' , ', $values) . " ] \n"; //on the browser change \n to <br>

    ob_end_flush();
    //ob_flush(); // enable on the browser
    flush();

    sleep(1); // wait one second
}