php实现双链表的删除和插入节点
2015-07-19 11:48
666 查看
<?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); } //插入节点 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; } } //从头输出节点 public function printFromFront(){ $p=$this->head->next; $string=""; while($p){ $string.=$string?",":""; $string.=$p->data; $p=$p->next; } echo $string."<br>"; } //从尾输出节点 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}的节点"; } } $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);
相关文章推荐
- php函数、类和对象以及类的封装、继承、类的静态方法、静态属性
- (一)PHP面向对象理论1---类
- php实现单链表
- php标签<?php ?>中的结束标签是否有必要添加
- [PHP开发] 关于header setcookie session_start 3个函数的怪问题
- php XML 读写 创建
- 54个提高PHP程序运行效率的方法
- ZendStudio导入一个已有的网站
- phprpc的使用示例以及报错Fatal error: Cannot redeclare gzdecode() in D:\wamp\www\immoc\phprpc\compat.php 处理
- php开发之数组排序
- 关于各种文件用Editplus的方式打开出现“向程序发送命令时出现问题”的解决方法
- php-编译安装
- PHP优化加速
- xinetd-ftpd 访问控制例子
- windows下配置php + mysql环境
- LAMP + Yii,并且隐藏Yii url的inde.php
- php自动加载
- PHP AJAXFORM提交图片上传并显示图片源码
- PHP接收多个上传文件
- 54个提高PHP程序运行效率的方法