【问题标题】:How to make a Circular linked list in php?如何在php中制作循环链表?
【发布时间】:2011-09-09 00:01:55
【问题描述】:

我在 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);

链表对象 ( [firstNode] => listNode 对象 ( [数据] => 1 [下一个] => )

[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] =>
                                    )

                            )

                    )

            )

    )

)

【问题讨论】:

  • PHP 已经支持数组,并且有许多函数来操作它们。您尝试实施链接列表是否有任何特殊原因(例如,家庭作业)?
  • 我把这当做家庭作业

标签: php algorithm linked-list circular-list


【解决方案1】:

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

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

您还需要确保在使用insertFirstinsertLast 添加更多节点时保持此链接,即在插入新的第一个/最后一个节点时始终设置lastNode-&gt;next = firstNode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多