美文网首页
Leetcode-Medium 2. Add Two Numbe

Leetcode-Medium 2. Add Two Numbe

作者: 致Great | 来源:发表于2019-02-21 11:28 被阅读2次

题目描述

给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。将两个数字相加并将其作为链接列表返回。

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

相关文章

网友评论

      本文标题:Leetcode-Medium 2. Add Two Numbe

      本文链接:https://www.haomeiwen.com/subject/pxwcyqtx.html