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

jacklove
发布: 2023-04-02 19:16:02
原创
1712 人浏览过

这篇文章主要介绍了PHP实现单链表翻转操作,结合实例形式分析了php单链表的定义、遍历、递归、翻转等相关操作技巧,需要的朋友可以参考下

本文实例讲述了PHP实现单链表翻转操作。分享给大家供大家参考,具体如下:

当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表。

这里给出了一个单链表的定义及翻转操作方法:

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实现单链表翻转操作示例讲解的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!