1. 程式人生 > >php連結串列筆記:合併兩個有序連結串列

php連結串列筆記:合併兩個有序連結串列

<?php
/**
 * Created by PhpStorm.
 * User: huizhou
 * Date: 2018/12/2
 * Time: 15:29
 */

/**
 * 合併兩個有序連結串列
 * 思路:簡單的合併排序。由於連結串列本來就是遞增的,所以每次將兩個連結串列中較小的部分拿過來就可以了。
 */

class MergeNode{
    private $next;
    private $value;

    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 test(){ // 建立兩個有序的連結串列 $linkList=new MergeNode(); $linkList->setNext(null); $temp=$linkList; for($i=1;$i<=10;$i+=2){ $node=new MergeNode(); $node->setValue($i); $node
->setNext(null); $temp->setNext($node); $temp=$node; } //第二個有序的連結串列 $list2=new MergeNode(); $temp=$list2; for($i=2;$i<=10;$i+=2){ $node=new MergeNode(); $node->setValue($i); $node->setNext(null); $temp->setNext($node); $temp=$node; } $result = Merge($linkList,$list2); while($result != null){ if($result->getValue()){ echo $result->getValue() .","; } $result = $result->getNext(); } } test(); /** * 合併兩個有序連結串列 * @param MergeNode $pHead1 * @param MergeNode $pHead2 * @return MergeNode */ function Merge(MergeNode $pHead1,MergeNode $pHead2){ if($pHead1 == null){ return $pHead2; } if($pHead2 == null){ return $pHead1; } if($pHead1->getValue() < $pHead2->getValue()){ $resultHead = $pHead1; $pHead1 = $pHead1->getNext(); }else{ $resultHead = $pHead2; $pHead2 = $pHead2->getNext(); } $pre = $resultHead; while ($pHead1 && $pHead2){ if($pHead1->getValue() <= $pHead2->getValue()){ $pre->setNext($pHead1); $pHead1 = $pHead1->getNext(); $pre = $pre->getNext(); }else{ $pre->setNext($pHead2); $pHead2 = $pHead2->getNext(); $pre = $pre->getNext(); } } if($pHead1 != null){ $pre->setNext($pHead1); } if($pHead2 !=null){ $pre->setNext($pHead2); } return $resultHead; }