看了很久数据结构但是没有怎么用过,在网上看到了关于PHP的数据结构,学习了一下,与大家一起分享一下。上一次分享了《PHP小教程之实现链表》,这次来补充说一下双向链表。
<?php<BR> class Hero<BR> {<BR> public $pre=null;<BR> public $no;<BR> public $name;<BR> public $next=null;<BR> public function __construct($no='',$name='')<BR> {<BR> $this->no=$no;<BR> $this->name=$name;<BR> }<BR> static public function addHero($head,$hero)<BR> {<BR> $cur = $head;<BR> $isExist=false;<BR> //判断目前这个链表是否为空<BR> if($cur->next==null)<BR> {<BR> $cur->next=$hero;<BR> $hero->pre=$cur;<BR> }<BR> else<BR> {<BR> //如果不是空节点,则安排名来添加<BR> //找到添加的位置<BR> while($cur->next!=null)<BR> {<BR> if($cur->next->no > $hero->no)<BR> {<BR> break;<BR> }<BR> else if($cur->next->no == $hero->no)<BR> {<BR> $isExist=true;<BR> echo "<br>不能添加相同的编号";<BR> }<BR> $cur=$cur->next;<BR> }<BR> if(!$isExist)<BR> {<BR> if($cur->next!=null)<BR> {<BR> $hero->next=$cur->next;<BR> }<BR> $hero->pre=$cur;<BR> if($cur->next!=null)<BR> {<BR> $hero->next->pre=$hero;<BR> }<BR> $cur->next=$hero; <BR> }<BR> }<BR> }<BR> //遍历<BR> static public function showHero($head)<BR> {<BR> $cur=$head;<BR> while($cur->next!=null)<BR> {<BR> echo "<br>编号:".$cur->next->no."名字:".$cur->next->name;<BR> $cur=$cur->next;<BR> }<BR> }<BR> static public function delHero($head,$herono)<BR> {<BR> $cur=$head;<BR> $isFind=false;<BR> while($cur!=null)<BR> {<BR> if($cur->no==$herono)<BR> {<BR> $isFind=true;<BR> break;<BR> }<BR> //继续找<BR> $cur=$cur->next;<BR> }<BR> if($isFind)<BR> {<BR> if($cur->next!=null)<BR> {<BR> $cur->next_pre=$cur->pre;<BR> }<BR> $cur->pre->next=$cur->next;<BR> }<BR> else<BR> {<BR> echo "<br>没有找到目标";<BR> } <BR> }<BR> }<BR> $head = new Hero();<BR> $hero1 = ne<b>/本文来源gao@!dai!ma.com搞$$代^@码5网@</b><strong>搞代gaodaima码</strong>w Hero(1,'1111');<BR> $hero3 = new Hero(3,'3333');<BR> $hero2 = new Hero(2,'2222');<BR> Hero::addHero($head,$hero1);<BR> Hero::addHero($head,$hero3);<BR> Hero::addHero($head,$hero2);<BR> Hero::showHero($head);<BR> Hero::delHero($head,2);<BR> Hero::showHero($head);<BR>?><BR>