本文實例講述了PHP實現雙鏈表刪除與插入節點的方法。分享給大家供大家參考,具體如下:
概述:
雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個數據結點中都有兩個指針,分別指向直接后繼和直接前驅。所以,從雙向鏈表中的任意一個結點開始,都可以很方便地訪問它的前驅結點和后繼結點。一般我們都構造雙向循環鏈表。
實現代碼:
?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);
}
//插入節點
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;
}
}
//從頭輸出節點
public function printFromFront(){
$p=$this->head->next;
$string="";
while($p){
$string.=$string?",":"";
$string.=$p->data;
$p=$p->next;
}
echo $string."br>";
}
//從尾輸出節點
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 "沒有值為{$data}的節點";
}
}
$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);
運行結果:
1,2,4,5
5,4,2,1,head
沒有值為6的節點
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數據結構與算法教程》、《php程序設計算法總結》、《php字符串(string)用法總結》、《PHP數組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結》及《PHP數學運算技巧總結》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- php遞歸調用刪除數組空值元素的方法
- PHP遞歸刪除多維數組中的某個值
- 實現php刪除鏈表中重復的結點
- 利用PHP實現遞歸刪除鏈表元素的方法示例