leetcode-2

@爱耍流氓的唐僧  November 6, 2021

使用php的对象实现链表的模式:

<?php 

class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val = 0, $next = null) {
        $this->val = $val;
        $this->next = $next;
    }
}
 

class Solution 
{
    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function addTwoNumbers($l1, $l2) 
    {
        $obj = null;
        
        $additional = 0;
        do {
            $value = $l1->val + $l2->val + $additional;
            if ($value < 10) {
                $additional = 0;
            } else {
                $value -= 10;
                $additional = 1;
            }
            
            $tmp_obj = new ListNode($value);
            
            if (is_null($obj)) {
                $obj = $tmp_obj;
            } else {
                $next->next = $tmp_obj;
            }
            $next = $tmp_obj;
            
            $l1 = $l1->next;
            $l2 = $l2->next;
            
        } while ($l1 || $l2 || $additional);
        
        return $obj;
    }
}

$a = new Solution();
$l6 = new ListNode(2);
$l5 = new ListNode(3,$l6);
$l4 = new ListNode(2);
$l3 = new ListNode(2,$l4);
$l1 = new ListNode(2,$l5);
$l2 = new ListNode(8,$l3);

var_dump($a->addTwoNumbers($l1,$l2));

添加新评论