002_Add Two Numbers

 

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

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur=ListNode(0)
        head=cur
        temp=0
        a=0
        while l1 and l2:
            a=l1.val+l2.val+temp
            temp=0
            if a>=10:
                temp=a//10
                a=a%10
            node=ListNode(a)
            cur.next=node
            l1=l1.next
            l2=l2.next
            cur=cur.next
        while l2:
            a=l2.val+temp
            temp=0
            if a>=10:
                temp=a//10
                a=a%10
            node=ListNode(a)
            cur.next=node
            l2=l2.next
            cur=cur.next
        while l1:
            a=l1.val+temp
            temp=0
            if a>=10:
                temp=a//10
                a=a%10
            node=ListNode(a)     
            cur.next=node
            l1=l1.next
            cur=cur.next
        if temp:
            node=ListNode(temp)
            cur.next=node
            cur=cur.next
        return head.next

  

posted @ 2019-04-17 22:48  灰灰的一只鸟  阅读(126)  评论(0编辑  收藏  举报