1 <?php 2 /**双向链表 -- 水浒传英雄排行版*/ 3 class hero{ 4 public $name = ''; 5 public $no =''; 6 public $cname = ''; 7 public $next = ''; 8 public $pre = ''; 9 public function __construct($no = '',$name='',$cname=''){ 10 $this->no = $no; 11 $this->name = $name; 12 $this->cname = $cname; 13 } 14 //显示英雄链表 15 public static function showHero($head){ 16 $cur = $head; 17 while($cur->next != null){ 18 echo '英雄编号:'.$cur->next->no.' '; 19 echo '英雄姓名:'.$cur->next->name.' '; 20 echo '英雄昵称:'.$cur->next->cname.' '; 21 echo '<br />'; 22 $cur = $cur->next; 23 } 24 echo '<hr />'; 25 } 26 //英雄按排序加入 27 public static function addHero($head,$hero){ 28 $cur = $head; 29 $isExits = false; 30 while($cur->next != null){ 31 if($cur->next->no > $hero->no){ 32 break; 33 }elseif($cur->next->no == $hero->no){ 34 $isExits = true; 35 } 36 $cur = $cur->next; 37 } 38 if(!$isExits){ 39 if($cur->next != null){ 40 $hero->next = $cur->next; 41 } 42 $hero->pre = $cur; 43 if($cur->next != null){ 44 $cur->next->pre = $hero; 45 } 46 $cur->next = $hero; 47 } 48 } 49 //修改英雄 50 public static function editHero($head,$hero){ 51 $cur = $head; 52 while($cur->next != null){ 53 if($cur->next == $hero){ 54 break; 55 } 56 $cur = $cur->next; 57 } 58 $cur->next->name = $hero->name; 59 $cur->next->cname = $hero->cname; 60 } 61 //删除英雄 62 public static function delHero($head,$hero){ 63 $cur = $head; 64 if($cur == null){ 65 return false; 66 } 67 while($cur->next != null){ 68 if($cur == $hero){ 69 break; 70 } 71 $cur = $cur->next; 72 } 73 if($cur->next != null){ 74 $cur->next->pre = $cur->pre; 75 } 76 $cur->pre->next = $cur->next; 77 } 78 } 79 80 $head = new hero(); 81 $songjiang = new hero(1,'宋江','及时雨'); 82 $lujunyi = new hero(2,'卢俊义','玉麒麟'); 83 $linchong = new hero(6,'林冲','豹子头'); 84 $wuyong = new hero(3,'吴用','智多星'); 85 hero::addHero($head,$songjiang); 86 hero::addHero($head,$lujunyi); 87 hero::addHero($head,$linchong); 88 hero::addHero($head,$wuyong); 89 hero::showHero($head); 90 $wuyong->name = '吴用2'; 91 hero::editHero($head,$wuyong); 92 hero::showHero($head); 93 hero::delHero($head,$wuyong); 94 hero::showHero($head); 95 ?> 96 </body> 97 </html>
源代码下载:DoubleLine_1202.zip