题目描述
给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。将两个数字相加并将其作为链接列表返回。
Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
思路
递归
代码实现
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): if l1 == None: return l2 if l2 == None: return l1 val = l1.val + l2.val ansnode=ListNode(val%10) ansnode.next=self.addTwoNumbers(l1.next,l2.next) if val>=10: ansnode.next=self.addTwoNumbers(ListNode(1),ansnode.next) return ansnode