本文實例講述了PHP實現單鏈表翻轉操作。分享給大家供大家參考,具體如下:
當一個序列中只含有指向它的后繼結點的鏈接時,就稱該鏈表為單鏈表。
這里給出了一個單鏈表的定義及翻轉操作方法:
?php * @file reverseLink.php * @author showersun * @date 2016/03/01 10:33:25html' target='_blank'>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 $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教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答