本文實(shí)例講述了PHP實(shí)現(xiàn)單鏈表翻轉(zhuǎn)操作。分享給大家供大家參考,具體如下:
當(dāng)一個(gè)序列中只含有指向它的后繼結(jié)點(diǎn)的鏈接時(shí),就稱該鏈表為單鏈表。
這里給出了一個(gè)單鏈表的定義及翻轉(zhuǎn)操作方法:
?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;//遍歷,將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)緩存后更改當(dāng)前節(jié)點(diǎn)指針 function reverse($head){ if($head == null){ return $head; $pre = $head;//注意:對(duì)象的賦值 $cur = $head- getNext(); $next = null; while($cur != null){ $next = $cur- getNext(); $cur- setNext($pre); $pre = $cur; $cur = $next; //將原鏈表的頭節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)置為null,再將反轉(zhuǎn)后的頭節(jié)點(diǎn)賦給head $head- setNext(null); $head = $pre; return $head;//遞歸,在反轉(zhuǎn)當(dāng)前節(jié)點(diǎn)之前先反轉(zhuǎn)后續(xù)節(jié)點(diǎn) 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; // 構(gòu)造一個(gè)長(zhǎng)度為10的鏈表,保存頭節(jié)點(diǎn)對(duì)象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();?
運(yùn)行結(jié)果:
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0您可能感興趣的文章:
PHP實(shí)現(xiàn)合并兩個(gè)有序數(shù)組的方法講解
PHP實(shí)現(xiàn)約瑟夫環(huán)問(wèn)題的方法詳解
Laravel5.5中利用Passport實(shí)現(xiàn)Auth認(rèn)證的方法講解
以上就是PHP實(shí)現(xiàn)單鏈表翻轉(zhuǎn)操作示例講解的詳細(xì)內(nèi)容,PHP教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選