我正在尝试对使用此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();
}
但是结果不同于动画:( 如何模仿这个双重链接列表动画并获得相同的结果?
答案 0 :(得分:1)
我认为您不能使用纯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
}