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(); ?>

运行结果:

更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《

希望本文所述对大家PHP程序设计有所帮助。

相关文章

如何选择合适的 C++ Web 开发框架?
利用 C++ 框架构建高并发 Web 应用的策略
用 C++ 框架开发跨平台图形应用程序
golang框架中安全编码实践的最佳指南是什么?
golang框架与其他语言框架在设计理念上的区别有哪些?
C++ 图形框架与其他语言框架的比较