PHP单链表翻转
2016-03-01 16:37
633 查看
<?php /** * @file reverseLink.php * @author showersun * @date 2016/03/01 10:33:25 **/ class Node{ private $value; private $next; public function __construct($value=null){ $this->value = $value; } public function getValue(){ return $this->value; } public function setValue($value){ $this->value = $value; } public function getNext(){ return $this->next; } public function setNext($next){ $this->next = $next; } } //遍历,将当前节点的下一个节点缓存后更改当前节点指针 function reverse($head){ if($head == null){ return $head; } $pre = $head;//注意:对象的赋值 $cur = $head->getNext(); $next = null; while($cur != null){ $next = $cur->getNext(); $cur->setNext($pre); $pre = $cur; $cur = $next; } //将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head $head->setNext(null); $head = $pre; return $head; } //递归,在反转当前节点之前先反转后续节点 function reverse2($head){ if (null == $head || null == $head->getNext()) { return $head; } $reversedHead = reverse2($head->getNext()); $head->getNext()->setNext($head); $head->setNext(null); return $reversedHead; } function test(){ $head = new Node(0); $tmp = null; $cur = null; // 构造一个长度为10的链表,保存头节点对象head for($i=1;$i<10;$i++){ $tmp = new Node($i); if($i == 1){ $head->setNext($tmp); }else{ $cur->setNext($tmp); } $cur = $tmp; } //print_r($head);exit; $tmpHead = $head; while($tmpHead != null){ echo $tmpHead->getValue().' '; $tmpHead = $tmpHead->getNext(); } echo "\n"; //$head = reverse($head); $head = reverse2($head); while($head != null){ echo $head->getValue().' '; $head = $head->getNext(); } } test(); ?>
相关文章推荐
- Git教程&PHP设计模式
- PHP对象赋值与克隆
- php设计模式 策略模式
- php中session锁--如何防止阻塞请求(译)
- 关于php数字转大写人民币的代码(完善)
- setSingleChoiceItems和setPositiveButton两者触发时期
- ThinkPHP5.0执行流程分析
- LAMP中php配置
- 在 Windows 上快速安装并运行 Laravel 5.x
- Wireshark 重组 FTP 会话
- php函数,伪函数的使用:函数名长,会影响到性能?
- php魔术方法——构造函数和析构函数
- PHP Ajax 跨域问题最佳解决方案
- smtplib 通过ssl端口发送邮件
- PHP内置函数和用户函数性能对比
- phpstudy易犯的错误
- Thinkphp5简单初体验
- 解析WordPress中控制用户登陆和判断用户登陆的PHP函数
- PHPExcel使用-使用PHPExcel导出文件-导出MySQL数据
- PHP函数中isset和array_key_exists的差异