2.两数相加

2.两数相加

 

方法一

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        p = head
        temp = 0
        while(l1 or l2):
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            s = temp + x + y
            temp = s // 10
            p.next = ListNode(s%10)
            p = p.next
            if(l1!=None):
                l1 = l1.next
            if(l2!=None):
                l2 = l2.next
        if(temp>0):
            p.next = ListNode(1)
        return head.next

 

posted @ 2019-01-18 11:26  小学弟-  阅读(116)  评论(0编辑  收藏  举报