2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def add_two_nums(l1, l2):
    carry, digit = 0, 0
    head, pre = None, None

    while l1 != None and l2 != None:
        digit = (l1.val + l2.val) % 10
        carry = (l1.val + l2.val) / 10
        l_new = ListNode(digit)
        if not head:
            head = l_new
        else:
            pre.next = l_new
        pre = l_new
        l1 = l1.next
        l2 = l2.next

    while l1 != None:
        digit = (l1.val + l2.carry) % 10
        carry = (l1.val + carry) / 10
        l_new = ListNode(digit)
        if not head:
            head = l_new
        else:
            pre.next = l_new
        pre = l_new
        l1 = l1.next

    while l2 != None:
        digit = (carry + l2.carry) % 10
        carry = (carry + carry) / 10
        l_new = ListNode(digit)
        if not head:
            head = l_new
        else:
            pre.next = l_new
        pre = l_new
        l2 = l2.next

    if carry > 0:
        l_new = ListNode(carry)
        pre.next = l_new

    return head


L3 = ListNode(3, ListNode(2, ListNode(1)))
L4 = ListNode(4, ListNode(3, ListNode(2)))

l_res = add_two_nums(L3, L4)

while l_res != None:
    print l_res.val,
    l_res = l_res.next

 

posted @ 2018-08-04 19:58  geeklove  阅读(134)  评论(0编辑  收藏  举报