Method Example of Deleting and Inserting Nodes in Double Linked List by PHP
- 2021-08-12 02:24:00
- OfStack
In this paper, an example is given to describe the method of deleting and inserting nodes in PHP. Share it for your reference, as follows:
Overview:
Two-way linked list is also called double linked list, which is a kind of linked list. There are two pointers in each data node, pointing to direct successor and direct precursor respectively. Therefore, starting from any one node in the bidirectional linked list, it is convenient to access its predecessor node and successor node. 1 We all construct bidirectional circular linked lists.
Implementation code:
<?php
class node{
public $prev;
public $next;
public $data;
public function __construct($data,$prev=null,$next=null){
$this->data=$data;
$this->prev=$prev;
$this->next=$next;
}
}
class doubleLinkList{
private $head;
public function __construct()
{
$this->head=new node("head",null,null);
}
// Insert node
public function insertLink($data){
$p=new node($data,null,null);
$q=$this->head->next;
$r=$this->head;
while($q){
if($q->data>$data){
$q->prev->next=$p;
$p->prev=$q->prev;
$p->next=$q;
$q->prev=$p;
}else{
$r=$q;$q=$q->next;
}
}
if($q==null){
$r->next=$p;
$p->prev=$r;
}
}
// Ab initio output node
public function printFromFront(){
$p=$this->head->next;
$string="";
while($p){
$string.=$string?",":"";
$string.=$p->data;
$p=$p->next;
}
echo $string."<br>";
}
// From tail output node
public function printFromEnd(){
$p=$this->head->next;
$r=$this->head;
while($p){
$r=$p;$p=$p->next;
}
$string="";
while($r){
$string.=$string?",":"";
$string.=$r->data;
$r=$r->prev;
}
echo $string."<br>";
}
public function delLink($data){
$p=$this->head->next;
if(!$p)
return;
while($p){
if($p->data==$data)
{
$p->next->prev=$p->prev;
$p->prev->next=$p->next;
unset($p);
return;
}
else{
$p=$p->next;
}
}
if($p==null)
echo " There is no value of {$data} Node of ";
}
}
$link=new doubleLinkList();
$link->insertLink(1);
$link->insertLink(2);
$link->insertLink(3);
$link->insertLink(4);
$link->insertLink(5);
$link->delLink(3);
$link->printFromFront();
$link->printFromEnd();
$link->delLink(6);
Run results:
1,2,4,5
5,4,2,1,head
There is no value of 6 Node of
For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"
I hope this article is helpful to everyone's PHP programming.