美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: 阿团相信梦想都能实现 | 来源:发表于2016-09-14 16:08 被阅读0次
    # 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
            """
            dummy=ListNode(-1)
            current=dummy
            carry=0
            while l1 or l2:
                val=carry
                if l1:
                    val+=l1.val
                    l1=l1.next
                if l2:
                    val+=l2.val
                    l2=l2.next
                    
                new_node=ListNode(val%10)
                current.next=new_node
                current=current.next
                carry=val/10
            if carry!=0:
                new_node=ListNode(carry)
                current.next=new_node
    
            return dummy.next  
    

    相关文章

      网友评论

          本文标题:2. Add Two Numbers

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