利用PHP怎么插入與刪除雙鏈表?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

概述:
雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個(gè)數(shù)據(jù)結(jié)點(diǎn)中都有兩個(gè)指針,分別指向直接后繼和直接前驅(qū)。所以,從雙向鏈表中的任意一個(gè)結(jié)點(diǎn)開(kāi)始,都可以很方便地訪問(wèn)它的前驅(qū)結(jié)點(diǎn)和后繼結(jié)點(diǎn)。一般我們都構(gòu)造雙向循環(huán)鏈表。
實(shí)現(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é)點(diǎn)
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é)點(diǎn)
public function printFromFront(){
$p=$this->head->next;
$string="";
while($p){
$string.=$string?",":"";
$string.=$p->data;
$p=$p->next;
}
echo $string."<br>";
}
//從尾輸出節(jié)點(diǎn)
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 "沒(méi)有值為{$data}的節(jié)點(diǎn)";
}
}
$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);運(yùn)行結(jié)果:
1,2,4,5 5,4,2,1,head 沒(méi)有值為6的節(jié)點(diǎn)
看完上述內(nèi)容,你們掌握利用PHP怎么插入與刪除雙鏈表的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
當(dāng)前文章:利用PHP怎么插入與刪除雙鏈表-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://www.chinadenli.net/article38/djdopp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、網(wǎng)站收錄、網(wǎng)站設(shè)計(jì)、Google、軟件開(kāi)發(fā)、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容