[LeetCode 系列] Add Two Numbers 的php解法

/ 0评 / 0
/**
 * 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 $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function addTwoNumbers($l1, $l2) {
        $result=(is_null($l1)?0:$l1->val)+(is_null($l2)?0:$l2->val);
        if($result>=10){
            $result-=10;
            if(is_null($l1->next)){
                $l1->next=new ListNode;
            }
            $l1->next->val+=1;
        }
        $node=new ListNode($result);
        if(is_null($l1->next) && is_null($l2->next)){
            return $node;
        }
        $node->next=$this->addTwoNumbers($l1->next,$l2->next);
        return $node;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注