In the next question from : the question_link

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

And write the following code

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

gives this error

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}

You can also see an image of the error and the code

enter image description here

When deleting (array) from line 25 to be

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

will give the error

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}

Screenshot with the error enter image description here

1

There are 1 best solutions below

0
mickmackusa On

You must not explicitly cast the array (which is already hardcoded as an array) as an array inside of array_push().

This is wrong: (Simple Demo)

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

Use this:

array_push($array, 'test');