为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕勒3428872 2021-11-13 19:08:08
我试图对使用此工具生成的双向链表动画进行逆向工程:所以我试过这个:<?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(); //rebobinandowhile ($dll->valid()) {    $current = $dll->current();    echo 'Atual: '.$current, "\n";    $dll->next();}但是结果与动画不同:(如何模仿这个双向链表动画并获得相同的结果?
查看完整描述

1 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

我不认为您可以使用纯 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

}


查看完整回答
反对 回复 2021-11-13
  • 1 回答
  • 0 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信