欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何在PHP項目中對單鏈表進行翻轉(zhuǎn)-創(chuàng)新互聯(lián)

如何在PHP項目中對單鏈表進行翻轉(zhuǎn)?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價值的長期合作伙伴,公司提供的服務項目有:國際域名空間、網(wǎng)站空間、營銷軟件、網(wǎng)站建設(shè)、橋東網(wǎng)站維護、網(wǎng)站推廣。
<?php

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,再將反轉(zhuǎn)后的頭節(jié)點賦給head 
  $head->setNext(null);
  $head = $pre;
  return $head;
}
//遞歸,在反轉(zhuǎn)當前節(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

看完上述內(nèi)容,你們掌握如何在PHP項目中對單鏈表進行翻轉(zhuǎn)的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

名稱欄目:如何在PHP項目中對單鏈表進行翻轉(zhuǎn)-創(chuàng)新互聯(lián)
文章地址:http://chinadenli.net/article4/ddgcoe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機、軟件開發(fā)、域名注冊、面包屑導航、企業(yè)建站營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務器托管