Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
时间复杂度: O(N)- 空间复杂度: O(1)
链表方向的题用php太麻烦了,可以尝试用Python
def addTwoNumber(l1,l2):
if not l1 and not l2:
return
elif not (l1 and l2):
return l1 or l2
else :
if l1.val + l2.val < 10:
l3 = ListNode(l1.val+l2.val)
l3.next = self.addTwoNumber(l1.next,l2.next)
else:
l3 = ListNode(l1.val+l2.val-10)
l3.next = self.addTwoNumber(l1.next,self.addTwoNumber(l2.next,ListNode(1)))
return l3