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

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

一、总结

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

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

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

题目描述:

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

三、代码

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

 1 <?php
 2 /*class ListNode{
 3     var $val;
 4     var $next = NULL;
 5     function __construct($x){
 6         $this->val = $x;
 7     }
 8 }*/
 9 //算法:直接用两个链表原来的节点连
10 function Merge($pHead1, $pHead2)
11 {
12     $arr=array();
13     while($pHead1&&$pHead2){
14         if($pHead1->val<=$pHead2->val) {$arr[]=$pHead1; $pHead1=$pHead1->next;}
15         else {$arr[]=$pHead2; $pHead2=$pHead2->next;}
16     }
17     while($pHead1){
18         $arr[]=$pHead1; $pHead1=$pHead1->next;
19     }
20     while($pHead2){
21         $arr[]=$pHead2; $pHead2=$pHead2->next;
22     }
23     for($i=0;$i<count($arr)-1;$i++){
24         $arr[$i]->next=$arr[$i+1];
25     }
26     $arr[count($arr)-1]->next=null;
27     return $arr[0];
28 }

代码二:

 1 <?php
 2 /*class ListNode{
 3     var $val;
 4     var $next = NULL;
 5     function __construct($x){
 6         $this->val = $x;
 7     }
 8 }*/
 9 //算法:直接用两个链表原来的节点连
10 function Merge($pHead1, $pHead2)
11 {
12     $head=new ListNode(0);//多了一个head节点 //1、这里一定要初始化值,不然是错的
13     $cur=$head;
14     while($pHead1&&$pHead2){
15         if($pHead1->val<=$pHead2->val) {$cur->next=$pHead1; $cur=$cur->next; $pHead1=$pHead1->next;} //2、$cur=$cur->next;这句话需要好好理解
16         else {$cur->next=$pHead2; $cur=$cur->next; $pHead2=$pHead2->next;}
17     }
18     while($pHead1){
19         $cur->next=$pHead1; $cur=$cur->next; $pHead1=$pHead1->next;
20     }
21     while($pHead2){
22         $cur->next=$pHead2; $cur=$cur->next; $pHead2=$pHead2->next;
23     }
24     return $head->next;//因为多建了head这个头节点
25 }
原文地址:https://www.cnblogs.com/Renyi-Fan/p/9061553.html