PHP 致命错误:未捕获错误:array_push():无法在 solution.php 中通过引用传递参数 #1($array) 合并两个排序列表中的堆栈跟踪

问题描述 投票:0回答:1

的下一个问题中:question_link

给定两个排序链表 list1 和 list2 的表头。 将两个列表合并为一个排序列表。该列表应该通过将前两个列表的节点拼接在一起来制作。 返回合并链表的头部。

并编写以下代码

/**
 * 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=[] ) {
         $count = (count((array)$list1) >= count((array)$list2)) ? count((array)$list1) : count((array)$list2);

       $list3[] = array();

        for ($i=0 ; $i < $count ; $i++){
            if(count((array)$list1) > $i){
                array_push( (array)$list3 , $list1[$i] );
            }
            if(count((array)$list2) > $i){
                array_push((array)$list3 , $list2[$i]  );
            }
        }

        return $list3;
    }
}

给出这个错误

Line 25: PHP Fatal error:  Uncaught Error: array_push(): Argument #1 ($array) cannot be passed by reference in solution.php
Stack trace:
#0 solution.php: Solution->mergeTwoLists()
#1 {main}

您还可以看到错误的图像和代码

enter image description here

从第25行删除(数组)时

        if(count((array)$list1) > $i){
              array_push( $list3 , $list1[$i] );
            }

会报错

Line 25: PHP Fatal error:  Uncaught Error: Cannot use object of type ListNode as array in solution.php
Stack trace:
#0 solution.php: Solution->mergeTwoLists()
#1 {main}

错误截图 enter image description here

php arrays oop array-push
1个回答
0
投票

您不得将数组(已经硬编码为数组)显式转换为

array_push()
中的数组。

这是错误的:(Simple Demo

$array = [];
array_push((array) $array, 'test');
//         ^^^^^^^- bad
var_export($array);

使用这个:

array_push($array, 'test');
© www.soinside.com 2019 - 2024. All rights reserved.