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; }