PHP實現(xiàn)雙鏈表刪除與插入節(jié)點的方法示例
本文實例講述了PHP實現(xiàn)雙鏈表刪除與插入節(jié)點的方法。分享給大家供大家參考,具體如下:
概述:
雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個數(shù)據(jù)結(jié)點中都有兩個指針,分別指向直接后繼和直接前驅(qū)。所以,從雙向鏈表中的任意一個結(jié)點開始,都可以很方便地訪問它的前驅(qū)結(jié)點和后繼結(jié)點。一般我們都構(gòu)造雙向循環(huán)鏈表。
實現(xiàn)代碼:
<?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);
}
//插入節(jié)點
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;
}
}
//從頭輸出節(jié)點
public function printFromFront(){
$p=$this->head->next;
$string="";
while($p){
$string.=$string?",":"";
$string.=$p->data;
$p=$p->next;
}
echo $string."<br>";
}
//從尾輸出節(jié)點
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}的節(jié)點";
}
}
$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);
運行結(jié)果:
1,2,4,5 5,4,2,1,head 沒有值為6的節(jié)點
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學(xué)運算技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP數(shù)組式訪問接口ArrayAccess用法分析
這篇文章主要介紹了PHP數(shù)組式訪問接口ArrayAccess用法,結(jié)合實例形式分析了數(shù)組式訪問接口ArrayAccess的概念、功能、實現(xiàn)與使用方法,需要的朋友可以參考下2017-12-12
PHP 開發(fā)環(huán)境配置(Zend Server安裝)
運行安裝文件(ZendServer-CE-php-5.3.2-5.0.1-Windows_x86.exe)開始安裝,選項請參照我的選擇。2010-04-04
php ignore_user_abort與register_shutdown_function 使用方法
php ignore_user_abort與register_shutdown_function 使用方法小結(jié)。2009-06-06

