php链表笔记:单链表反转
生活随笔
收集整理的這篇文章主要介紹了
php链表笔记:单链表反转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?php /*** Created by PhpStorm.* User: huizhou* Date: 2018/12/1* Time: 11:41*//*** 1.鏈表的反轉* Class Node*/ 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(Node $head){if($head == null){return $head;}$pre = $head; // 取出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(Node $head){if($head == null || $head->getNext() == null){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的鏈表,保存頭節點對象headfor ($i = 1;$i < 10 ; $i++){$tmp = new Node($i);if ($i == 1){$head->setNext($tmp);}else{$cur->setNext($tmp);}$cur = $tmp;}$tmpHead = $head;while ($tmpHead != null){echo $tmpHead->getValue();$tmpHead = $tmpHead->getNext();}echo "\n";$head = reverse2($head);while ($head != null ){echo $head->getValue();$head = $head->getNext();}}test();
?
轉載于:https://www.cnblogs.com/mrszhou/p/10053307.html
總結
以上是生活随笔為你收集整理的php链表笔记:单链表反转的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 欠钱不还多少钱可以起诉?
- 下一篇: 医不育症的费用