php鏈表筆記:單鏈表反轉


<?php
/**
 * Created by PhpStorm.
 * User: huizhou
 * Date: 2018/12/1
 * Time: 11:41
 */

/**
 * 1.鏈表的反轉
 * Class Node
 */
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(Node $head){

       if($head == null){
           return $head;
       }

       $pre = $head; // 取出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(Node $head){
       if($head == null || $head->getNext() == null){
           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;
        }

        $tmpHead = $head;
        while ($tmpHead != null){
            echo $tmpHead->getValue();
            $tmpHead = $tmpHead->getNext();
        }

        echo "\n";

        $head = reverse2($head);

        while ($head != null ){
            echo $head->getValue();
            $head = $head->getNext();
        }
    }

    test();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM