You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode合并两个有序链表PHP代码报错求助

错误原因分析

核心问题:对链表结构的理解偏差

你完全把ListNode对象当成数组来操作,这是所有报错的根源:

  • ListNode是单链表的节点对象,不是数组,不能用$list1[$i]的方式访问节点,也不能通过count((array)$list1)获取链表长度(转数组后得到的是对象的属性列表,不是节点数量)。
  • 第一个报错:array_push()要求第一个参数是可引用的变量,(array)$list3是临时转换的数组,无法作为引用传递,因此触发错误。
  • 第二个报错:直接用数组下标访问ListNode对象,PHP不允许这种操作,所以报错。
修正方案

正确思路是用双指针遍历两个有序链表,逐个比较节点值,将较小的节点接入新链表,直到其中一个链表遍历完毕,再把剩余链表直接接入新链表末尾。

修正后的PHP代码:

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution {
    /**
     * @param ListNode $list1
     * @param ListNode $list2
     * @return ListNode
     */
    function mergeTwoLists($list1, $list2) {
        // 创建哑节点,简化头节点处理
        $dummy = new ListNode(0);
        $current = $dummy;
        
        // 双指针遍历两个链表
        while ($list1 !== null && $list2 !== null) {
            if ($list1->val <= $list2->val) {
                $current->next = $list1;
                $list1 = $list1->next;
            } else {
                $current->next = $list2;
                $list2 = $list2->next;
            }
            $current = $current->next;
        }
        
        // 接入剩余未遍历完的链表
        $current->next = $list1 !== null ? $list1 : $list2;
        
        return $dummy->next;
    }
}

代码说明

  • 哑节点$dummy:避免处理空链表的特殊情况,直接从$dummy->next返回合并后的头节点。
  • 双指针遍历:每次取两个链表当前节点中值较小的那个,接入新链表,然后移动对应指针。
  • 剩余节点处理:当其中一个链表遍历完后,直接将另一个链表的剩余部分接入新链表,因为原链表本身是有序的。

内容的提问来源于stack exchange,提问作者zico hipe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:39:20