PHP實現(xiàn)雙鏈表刪除與插入節(jié)點的方法示例
本文實例講述了PHP實現(xiàn)雙鏈表刪除與插入節(jié)點的方法。分享給大家供大家參考,具體如下:
概述:
雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個數(shù)據(jù)結點中都有兩個指針,分別指向直接后繼和直接前驅。所以,從雙向鏈表中的任意一個結點開始,都可以很方便地訪問它的前驅結點和后繼結點。一般我們都構造雙向循環(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);
運行結果:
1,2,4,5 5,4,2,1,head 沒有值為6的節(jié)點
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結構與算法教程》、《php程序設計算法總結》、《php字符串(string)用法總結》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結》及《PHP數(shù)學運算技巧總結》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
PHP實現(xiàn)服務器狀態(tài)監(jiān)控的方法
這篇文章主要介紹了PHP實現(xiàn)服務器狀態(tài)監(jiān)控的方法,可實現(xiàn)對指定IP服務器狀態(tài)的有效監(jiān)控,非常具有實用價值,需要的朋友可以參考下2014-12-12LINUX下PHP程序實現(xiàn)WORD文件轉化為PDF文件的方法
這篇文章主要介紹了LINUX下PHP程序實現(xiàn)WORD文件轉化為PDF文件的方法,涉及php針對Word文檔與pdf格式文件的相關操作技巧,需要的朋友可以參考下2016-05-05PHP高并發(fā)高負載下的3種實戰(zhàn)場景解決方法示例
這篇文章主要為大家介紹了PHP高并發(fā)高負載下的3種實戰(zhàn)場景解決方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05PHP使用pcntl_fork實現(xiàn)多進程下載圖片的方法
這篇文章主要介紹了PHP使用pcntl_fork實現(xiàn)多進程下載圖片的方法,較為詳細的分析了pcntl_fork的原理與用法,以及使用pcntl_fork實現(xiàn)多進程下載圖片的方法,非常具有實用價值,需要的朋友可以參考下2014-12-12關于php程序報date()警告的處理(date_default_timezone_set)
PHP Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function2013-10-10