mycode 87.22%

# 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 = link = ListNode(-1)
        add = 0
        while l1 and l2:
            temp = l1.val + l2.val + add
            if temp >= 10:
                link.next = ListNode(temp%10)
                add = temp // 10
            else:
                add = 0
                link.next = ListNode(temp)
            print(temp)
            l1 = l1.next
            l2 = l2.next
            link = link.next
        l1 = l1 or l2
        while l1:
            temp = l1.val + add
            if temp >= 10:
                link.next = ListNode(temp%10)
                add = temp // 10
            else:
                add = 0
                link.next = ListNode(temp)
            print(temp)
            l1 = l1.next
            link = link.next
        if add:
            link.next = ListNode(add)
            link = link.next
        link.next = None
        return dummy.next
            
        

参考:

1、如何把其中一个为None放到while里面去?

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy = link = ListNode(-1)
        add = 0
        while l1 or l2:
            res = 0
            if not l2: l2 = ListNode(0)
            if not l1:
                l1 = ListNode(0)
            temp = l1.val + l2.val + add
            print('temp...',temp+add)
            if temp > 9:
                res = temp % 10 
                add = temp // 10  
                #print('if...',res,add)
            else:
                res = temp
                add = 0
                #print('else...',res,add)
            l1 = l1.next
            l2 = l2.next
            dummy.next = ListNode(res)
            dummy = dummy.next
        if add > 0:
            print('addd...')
            dummy.next = ListNode(add)
            dummy = dummy.next
            dummy.next = None
        return link.next

 

2、如何把进位也放进去?

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        dummy = cur = ListNode(0)
        curry = 0
        while l1 or l2 or curry:
            if l1:
                curry = curry+l1.val
                l1 = l1.next
            if l2:
                curry = curry+l2.val
                l2 = l2.next
            cur.next = ListNode(curry%10)
            cur = cur.next
            curry = curry//10       
        return dummy.next

 

5Longest Palindromic Substring