PHP實現(xiàn)單鏈表翻轉(zhuǎn)操作示例
本文實例講述了PHP實現(xiàn)單鏈表翻轉(zhuǎn)操作。分享給大家供大家參考,具體如下:
當(dāng)一個序列中只含有指向它的后繼結(jié)點的鏈接時,就稱該鏈表為單鏈表。
這里給出了一個單鏈表的定義及翻轉(zhuǎn)操作方法:
<?php
/**
* @file reverseLink.php
* @author showersun
* @date 2016/03/01 10:33:25
**/
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é)點的下一個節(jié)點緩存后更改當(dāng)前節(jié)點指針
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;
}
//將原鏈表的頭節(jié)點的下一個節(jié)點置為null,再將反轉(zhuǎn)后的頭節(jié)點賦給head
$head->setNext(null);
$head = $pre;
return $head;
}
//遞歸,在反轉(zhuǎn)當(dāng)前節(jié)點之前先反轉(zhuǎn)后續(xù)節(jié)點
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)造一個長度為10的鏈表,保存頭節(jié)點對象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();
?>
運行結(jié)果:
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學(xué)運算技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
php統(tǒng)計數(shù)組不同元素的個數(shù)的實例方法
在本篇文章里小編給大家整理的是關(guān)于php統(tǒng)計數(shù)組不同元素的個數(shù)的實例方法以及相關(guān)知識點,有需要的朋友們學(xué)習(xí)下。2019-09-09
php小技巧 把數(shù)組的鍵和值交換形成了新的數(shù)組,查找值取得鍵
php小技巧--把數(shù)組的鍵和值交換形成了新的數(shù)組,查找值取得鍵的實現(xiàn)方法。2011-06-06
php實現(xiàn)根據(jù)字符串生成對應(yīng)數(shù)組的方法
這篇文章主要介紹了php實現(xiàn)根據(jù)字符串生成對應(yīng)數(shù)組的方法,包含了數(shù)組操作的技巧及eval函數(shù)的用法,需要的朋友可以參考下2014-09-09
PHP開發(fā)不能違背的安全規(guī)則 過濾用戶輸入
作為PHP程序員,特別是新手,對于互聯(lián)網(wǎng)的險惡總是知道的太少,對于外部的入侵有很多時候是素手無策的,他們根本不知道黑客是如何入侵的、提交入侵、上傳漏洞、sql 注入、跨腳本攻擊等等。2011-05-05

