记录leetcode两数相加(2)解法

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not (l1 or l2):
            # all the none
            return l1
        else:
            s = l1.val+l2.val
            flag = s/10
            head = ListNode(s%10)
            res = head
            # it is the import
            while l1.next != None or l2.next != None:
                l1 = l1.next if l1.next != None else ListNode(0)
                l2 = l2.next if l2.next != None else ListNode(0)
                s = l1.val+l2.val + flag
                flag = s/10
                head.next = ListNode(s%10)
                head = head.next
            if flag == 1:
                head.next = ListNode(flag)
                head = head.next
            return res

结果:

发布了45 篇原创文章 · 获赞 1 · 访问量 8574

猜你喜欢

转载自blog.csdn.net/qq_32110859/article/details/98909822