我在php中创建了一个链表 现在我想通知它,任何帮助都非常感激
linkedList的代码
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] =&gt; listNode对象 ( [data] =&gt; 1 [next] =&gt; )
[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] =>
)
)
)
)
)
)
答案 0 :(得分:2)
假设您的代码正常工作并为链表建立正确的数据结构,将其设为循环只是使最后一个节点指向第一个节点,例如:
$this->lastNode->next = $this->firstNode;
当您再添加insertFirst
或insertLast
的节点时,还需要确保维护此链接,即在插入新的第一个/最后一个节点时始终设置lastNode->next = firstNode
。