关于php:Add-Two-Numbers-的php解法

6次阅读

共计 608 个字符,预计需要花费 2 分钟才能阅读完成。

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

集体博客:https://www.gwlin.com/posts/5717

正文完
 0