0

我已经在 php 中创建了一个链表,现在我希望将其设为循环,非常感谢任何帮助

链接列表的代码

class listNode{


    public $data;
    public  $next;

    public function __construct($data)
    {
        $this->data=$data;
        $this->next=null;
    }
}


class linkedList {

    public $firstNode;

    public $lastNode;

    public $link;





    public function __construct()
    {
        $this->firstNode = NULL;
        $this->lastNode = NULL;
        $this->link=NULL;
    }

    public function insertFirst($data)
    {


        $tempStore=new listNode($data);
        $this->firstNode=clone($tempStore);
        $tempStore->next=$this->link;

        $this->link=$tempStore;


        if($this->lastNode == NULL){
            $this->lastNode = $this->link;
            }

    }

    public function insertLast($data)
    {

        if($this->firstNode==null)
        {
            $this->insertFirst($data);
        }else{
            $tempStore=new listNode($data);
            $this->lastNode->next=$tempStore;

            print_r($this->lastNode);
            $this->lastNode=$tempStore;
            print_r($this->lastNode);

        }

    }


    public function makeCircular()
    {



    }
} 




$totalNodes=5;

$theList = new linkedList();

for($i=1; $i <= $totalNodes; $i++)
{
    $theList->insertLast($i);
}


print_r($theList);

linkedList 对象 ( [firstNode] => listNode 对象 ( [data] => 1 [next] => )

[lastNode] => listNode Object
    (
        [data] => 5
        [next] =>
    )

[link] => listNode Object
    (
        [data] => 1
        [next] => listNode Object
            (
                [data] => 2
                [next] => listNode Object
                    (
                        [data] => 3
                        [next] => listNode Object
                            (
                                [data] => 4
                                [next] => listNode Object
                                    (
                                        [data] => 5
                                        [next] =>
                                    )

                            )

                    )

            )

    )

)

4

1 回答 1

2

假设您的代码正常工作并为链表构建正确的数据结构,使其循环只是使最后一个节点指向第一个节点的问题,例如:

$this->lastNode->next = $this->firstNode;

您还需要确保在使用insertFirstor添加更多节点时维护此链接insertLast,即始终lastNode->next = firstNode在插入新的第一个/最后一个节点时设置。

于 2011-09-09T00:50:09.277 回答