美文网首页
LeetCode 2. Add Two Numbers

LeetCode 2. Add Two Numbers

作者: 费城的二鹏 | 来源:发表于2018-11-14 13:52 被阅读1次

单链表逆序相加

class Solution:
    def addTwoNumbers(self, l1, l2):

        root = None
        pos = None
        sum = 0
        result = []
        while sum > 0 or l1 != None or l2 != None:

            v = 0
            if l1 != None:
                v = v + l1.val
                l1 = l1.next

            if l2 != None:
                v = v + l2.val
                l2 = l2.next

            sum = sum + v

            v = sum % 10
            sum = int(sum/10)

            node = ListNode(v)
            if root == None:
                root = node

            if pos == None:
                pos = node
            else:
                pos.next = node
                pos = node

        return root

相关文章

网友评论

      本文标题:LeetCode 2. Add Two Numbers

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