php連結串列

qq_35370923發表於2019-01-23
<?php
class Node{//節點類
    public $next;
    public $value;

    public function __construct($node)
    {

        $this->value = $node;

    }
}

class Link{//連結串列類
    public  $head = null;

    public function __construct($node)
    {
        if ($node instanceof Node){
            $this->head = $node;
        }

    }

    public function addNode($node){//尾插法
        $cur = $this->head;
        while($cur->next!=null){
            $cur = $cur->next;
        }
        $cur->next = $node;
    }

    public function linkList(){
        $cur = $this->head;
        while($cur!=null){
            echo $cur->value."<br>";
            $cur = $cur->next;
        }
    }

}
$head = new Node(1);
$link = new Link($head);

$link->addNode(new Node(2));
$link->addNode(new Node(3));
$link->addNode(new Node(4));
$link->addNode(new Node(5));
$newLink = reverse($link);
$newLink->linkList();

function reverse($link){//單連結串列逆序
    
    $pre = $link->head;
    $cur = $pre->next;
    $next= null;
    while($cur!=null){
        $next = $cur->next;
        $cur->next = $pre;
        $pre = $cur;
        $cur = $next;
    }
    $link->head->next = null;//這裡注意,下面好像已經重新賦值,這句話沒意義???類的物件這種重新賦值,類似於指標
    $link->head = $pre;//這裡的賦值,類似於指標,原來的頭節點其實沒有變化
    return $link;
}

相關文章