How to make a Circular linked list in php?
I have made a single linkedlist in php now i wish to make it circular , any help is really appreciated
code for 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 Object ( [firstNode] => listNode Object ( [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] =>
)
)
)
)
)
)
Assuming your code works correctly and builds the correct data structure for the linked list, making it circular is just a matter of making the last node point to the first node, e.g.:
$this->lastNode->next = $this->firstNode;
You also need to make sure this link is maintained when you then add more nodes with insertFirst
or insertLast
, i.e. always set lastNode->next = firstNode
when a new first/last node is inserted.
精彩评论