php实现合并两个排序的链表(很多情况下新建数组装东西比连东西逻辑快很多)($cur=$cur->next;的理解)

时间:2023-03-09 18:11:06
php实现合并两个排序的链表(很多情况下新建数组装东西比连东西逻辑快很多)($cur=$cur->next;的理解)

php实现合并两个排序的链表(很多情况下新建数组装东西比连东西逻辑快很多)($cur=$cur->next;的理解)

一、总结

$cur=$cur->next;这句话需要好好理解 
$cur的值现在等于$cur的next域的值,$cur的next域的值就是一个地址,指向的就是$cur的下一个节点
那整句话就是表示的是$cur的值就是下一个节点的地址值

这里出现了 $cur的值$cur的next域的值,以及还有的$cur的val域的值,所以就出现了三个值

php实现合并两个排序的链表(很多情况下新建数组装东西比连东西逻辑快很多)($cur=$cur->next;的理解)

二、php实现合并两个排序的链表

题目描述:

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

三、代码

代码一ac:直接用数组保存节点(很多情况下新建数组装东西比连东西逻辑快很多),因为这里数组里面装都是引用(地址),所以空间开销其实也没有大特别多

 <?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
//算法:直接用两个链表原来的节点连
function Merge($pHead1, $pHead2)
{
$arr=array();
while($pHead1&&$pHead2){
if($pHead1->val<=$pHead2->val) {$arr[]=$pHead1; $pHead1=$pHead1->next;}
else {$arr[]=$pHead2; $pHead2=$pHead2->next;}
}
while($pHead1){
$arr[]=$pHead1; $pHead1=$pHead1->next;
}
while($pHead2){
$arr[]=$pHead2; $pHead2=$pHead2->next;
}
for($i=0;$i<count($arr)-1;$i++){
$arr[$i]->next=$arr[$i+1];
}
$arr[count($arr)-1]->next=null;
return $arr[0];
}

代码二:

 <?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
//算法:直接用两个链表原来的节点连
function Merge($pHead1, $pHead2)
{
$head=new ListNode(0);//多了一个head节点 //1、这里一定要初始化值,不然是错的
$cur=$head;
while($pHead1&&$pHead2){
if($pHead1->val<=$pHead2->val) {$cur->next=$pHead1; $cur=$cur->next; $pHead1=$pHead1->next;} //2、$cur=$cur->next;这句话需要好好理解
else {$cur->next=$pHead2; $cur=$cur->next; $pHead2=$pHead2->next;}
}
while($pHead1){
$cur->next=$pHead1; $cur=$cur->next; $pHead1=$pHead1->next;
}
while($pHead2){
$cur->next=$pHead2; $cur=$cur->next; $pHead2=$pHead2->next;
}
return $head->next;//因为多建了head这个头节点
}