首頁  >  文章  >  後端開發  >  PHP實作單鍊錶翻轉操作範例講解

PHP實作單鍊錶翻轉操作範例講解

jacklove
jacklove原創
2018-07-06 17:56:181730瀏覽

這篇文章主要介紹了PHP實作單鍊錶翻轉操作,結合實例形式分析了php單鍊錶的定義、遍歷、遞歸、翻轉等相關操作技巧,需要的朋友可以參考下

本文實例講述了PHP實作單鍊錶翻轉操作。分享給大家供大家參考,具體如下:

當一個序列中只含有指向它的後繼結點的連結時,就稱該鍊錶為單鍊錶。

這裡給了一個單鍊錶的定義及翻轉操作方法:

##

<?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;
  }
}
//遍历,将当前节点的下一个节点缓存后更改当前节点指针 
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;
  }
  //将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head 
  $head->setNext(null);
  $head = $pre;
  return $head;
}
//递归,在反转当前节点之前先反转后续节点 
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的链表,保存头节点对象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().&#39; &#39;;
    $tmpHead = $tmpHead->getNext();
  }
  echo "\n";
  //$head = reverse($head);
  $head = reverse2($head);
  while($head != null){
    echo $head->getValue().&#39; &#39;;
    $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實作約瑟夫環問題的方法詳解

##########Laravel5.5中利用Passport實作Auth認證的方法講解####### #####################

以上是PHP實作單鍊錶翻轉操作範例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn