php实现单链表
2015-07-19 11:04
567 查看
<?php class node{ public $data; public $next; public function __construct($data=null,$next=null){ $this->data=$data; $this->next=$next; } } class SingleLinkList{ private $head; public function __construct(){ $this->head=new node("head",null); } //获取链表长度 public function getLength(){ $p=$this->head->next; $n=1; while($p){ $p=$p->next; $n++; } return $n; } //增加节点 public function addLink($data){ $p=new node($data); $q=$this->head->next; $r=$this->head; while($q){ $r=$q;$q=$q->next; } $r->next=$p; } //删除节点 public function delLink($data){ $p=$this->head->next; $q=$this->head; while($p->data!=$data && $p->next!=null && $p!=null){ $q=$p;$p=$p->next; } if($p->data==$data){ if($q==$this->head){ $this->head->next=$p->next; unset($p); } else{ $q->next=$p->next; unset($p); } }else{ echo "没有找到值为{$data}的节点"; } } //打印链表 public function printLink(){ $p=$this->head->next; $string=""; while($p){ $string.=$string?",":""; $string.=$p->data; $p=$p->next; } echo $string."<br>"; } //链表排序 public function sortLink(){ $len=$this->getLength(); if($this->head->next==null) return; for($i=0;$i<$len;$i++){ $p=$this->head->next; for($j=0;$j<$len-$i;$j++){ $q=$p->next; if($q->data!=null && $q!=null && $q->data<$p->data){ $temp=$p->data; $p->data=$q->data; $q->data=$temp; }else{ $p=$p->next; } } } } //链表逆置 public function reverseLink(){ $p=$this->head->next; $q=$p->next; if($p==null || $q==null) return; $p->next=null; while($q){ $r=$q->next; $q->next=$p; $p=$q; $q=$r; } $this->head->next=$p; } } $list=new SingleLinkList(); $list->addLink(5); $list->addLink(4); $list->addLink(3); $list->addLink(2); $list->addLink(1); $list->printLink(); $list->delLink(3); $list->printLink(); $list->sortLink(); $list->printLink(); $list->reverseLink(); $list->printLink();
相关文章推荐
- 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程序运行效率的方法
- php实现上传图片文件代码
- php上下箭头排序
- php无限级分类并把末级产品展示出来的思路