php鏈表筆記:單鏈表反轉
阿新 • • 發佈:2018-12-02
指向 一個 筆記 nbsp 遍歷 \n col next this
<?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; } publicfunction 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的鏈表,保存頭節點對象head for ($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();
php鏈表筆記:單鏈表反轉