题目
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
Go
执行用时:12 ms
内存消耗:5.1 MB
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
return handleNode(l1,l2,0)
}
func handleNode(l1 *ListNode, l2 *ListNode, carry int) *ListNode {
if l1 == nil && l2 == nil {
if carry == 0 {
return nil
}
return &ListNode{Val:carry}
}
if l1 == nil {
l1 = &ListNode{Val:0}
}
if l2 == nil {
l2 = &ListNode{Val:0}
}
sum := l1.Val + l2.Val + carry
l := &ListNode{Val:sum%10}
l.Next = handleNode(l1.Next, l2.Next, sum/10)
return l
}
PHP
执行用时 :24 ms
内存消耗 :15.1 MB
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function addTwoNumbers($l1, $l2) {
return $this->handleNode($l1, $l2, 0);
}
function handleNode($l1, $l2, $carry) {
if (!$l1 && !$l2) {
if (!$carry) {
return null;
}
return new ListNode($carry);
}
$x = $l1 ? $l1->val : 0;
$y = $l2 ? $l2->val : 0;
$sum = $x + $y + $carry;
if ($l1) {
$l1 = $l1->next;
}
if ($l2) {
$l2 = $l2->next;
}
$l = new ListNode($sum%10);
$l->next = $this->handleNode($l1, $l2, (int)($sum/10));
return $l;
}
}