PHP實現(xiàn)單鏈表翻轉操作示例
更新時間:2017年12月06日 15:11:37 作者:Shower稻草人
這篇文章主要介紹了PHP實現(xiàn)單鏈表翻轉操作,結合實例形式分析了php單鏈表的定義、遍歷、遞歸、翻轉等相關操作技巧,需要的朋友可以參考下
本文實例講述了PHP實現(xià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;
}
}
//遍歷,將當前節(jié)點的下一個節(jié)點緩存后更改當前節(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,再將反轉后的頭節(jié)點賦給head
$head->setNext(null);
$head = $pre;
return $head;
}
//遞歸,在反轉當前節(jié)點之前先反轉后續(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;
// 構造一個長度為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();
?>
運行結果:
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結構與算法教程》、《php程序設計算法總結》、《php字符串(string)用法總結》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結》及《PHP數(shù)學運算技巧總結》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
如何在PHP環(huán)境中使用ProtoBuf數(shù)據(jù)格式
這篇文章主要介紹了如何在PHP環(huán)境中使用ProtoBuf數(shù)據(jù)格式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
詳解Swoole跟傳統(tǒng)的web開發(fā)的區(qū)別
Swoole高效跟傳統(tǒng)的web開發(fā)有什么區(qū)別,除了傳統(tǒng)的LAMP/LNMP同步開發(fā)模式,swoole的異步開發(fā)模式是怎么樣的。本文帶著大家來詳細介紹一下。2021-05-05
php基于str_pad實現(xiàn)卡號不足位數(shù)自動補0的方法
這篇文章主要介紹了php基于str_pad實現(xiàn)卡號不足位數(shù)自動補0的方法,對于生成固定位數(shù)號碼的應用非常具有實用價值,需要的朋友可以參考下2014-11-11

