您好,欢迎访问一九零五行业门户网

PHP实现单链表翻转操作示例讲解

这篇文章主要介绍了php实现单链表翻转操作,结合实例形式分析了php单链表的定义、遍历、递归、翻转等相关操作技巧,需要的朋友可以参考下
本文实例讲述了php实现单链表翻转操作。分享给大家供大家参考,具体如下:
当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表。
这里给出了一个单链表的定义及翻转操作方法:
<?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();?>
运行结果:
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0
您可能感兴趣的文章:php实现合并两个有序数组的方法讲解
php实现约瑟夫环问题的方法详解
laravel5.5中利用passport实现auth认证的方法讲解
以上就是php实现单链表翻转操作示例讲解的详细内容。
其它类似信息

推荐信息