国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

PHP實(shí)現(xiàn)單鏈表翻轉(zhuǎn)操作示例

2024-05-05 00:01:20
字體:
供稿:網(wǎng)友

本文實(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: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é)點(diǎn)的下一個(gè)節(jié)點(diǎn)緩存后更改當(dāng)前節(jié)點(diǎn)指針 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é)點(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è)長度為10的鏈表,保存頭節(jié)點(diǎn)對象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();?>

運(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è)計(jì)有所幫助。


注:相關(guān)教程知識閱讀請移步到PHP教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 龙南县| 汝阳县| 西安市| 密云县| 萝北县| 阳山县| 黔南| 肃南| 博乐市| 新郑市| 洛宁县| 固阳县| 武城县| 泉州市| 天津市| 阜阳市| 芮城县| 井研县| 黄山市| 巴塘县| 承德县| 定南县| 舞阳县| 新安县| 洪湖市| 湘阴县| 邹平县| 博白县| 织金县| 文水县| 正蓝旗| 翼城县| 陕西省| 乌海市| 佛山市| 淳化县| 龙川县| 永康市| 新竹县| 肥东县| 昌邑市|