清华大学韩顺平讲师讲算法之三(下),环链表创建与删除

来源:互联网 发布:黑马程序员 c 课件 编辑:程序博客网 时间:2024/05/17 07:25
<html><head><meta http-equiv='content-type' content='text/html;charset=utf-8'><title>/高性能的计算器/</title></head><body><?phpclass Hero{public $pre=null;//指向前一个节点的引用public $no;public $name;public $nickname;public $next=null;public function __construct($no='',$name='',$nickname=''){$this->no=$no;$this->name=$name;$this->nickname=$nickname;}public static function addHero($head,$hero){$cur=$head;//一个辅助点,不能动头$isExist=false;if($cur->next==null){$cur->next=$hero;$hero->pre=$cur;}else{///如果不是空节点,则按排名来添加while($cur->next!=null){if($cur->next->no>$hero->no){//说明$hero要加入在$cur的后面}else if($cur->next->no==$hero->no){$isExist=true;echo '<br>不能有相同编号';}$cur=$cur->next;}//while// 退出while时,我们只要把$hero添加到$cure后面即可if(!$isExist){//比如加的就是末if($cur->next !=null){//处理空表$hero->next=$cur->next;}$hero->pre=$cur;if($cur->next !=null){//处理空表$cur->next->pre=$hero;}$cur->next=$hero;}}//if}//addHeropublic static function showHero($head){$cur=$head;while($cur->next !=null){echo '<br>编号:'.$cur->no.'名字:'.$cur->name;$cur=$cur->next;}//当退出whileecho '<br>编号是:'.$cur->no.'名字:'.$cur->name;}//showHeropublic static function delHero($head,$herono){//不用辅助结点$cur=$head->next;if($cur==null){echo '一个空表,删除了没意义';}$isFind=false;while ($cur !=null) {if($cur->no == $herono){//找到了$isFind=true;break;}//if$cur=$cur->next;//向下找}//whileif($isFind){//找到了可以删除//自我删除,不使用辅助结点if($cur->next !=null){$cur->next->pre=$cur->pre;}$cur->pre->next=$cur->next;}else{echo "找不到了,你输入的不对,没法子删除啊.";}//if}//delHero}//class$head=new Hero();$hero=new Hero(1,'宋江','及时狗');Hero::addHero($head,$hero);$hero=new Hero(2,'吴用','一个老师');Hero::addHero($head,$hero);$hero=new Hero(3,'林冲','教头');Hero::addHero($head,$hero);Hero::showHero($head);//试试删除Hero::delHero($head,2);//echo '<br>'."删除的后的".'<br>';Hero::showHero($head);echo '<br><br>'.'其好处是自好删除,以后学习二叉树及其他,打下良好的基础';?></body></html>

原创粉丝点击