首页 > 代码库 > 2、Add Two Numbers

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

python代码段

# 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
        """

        tag = 0
        if l1.val+l2.val>9:
            l3 = ListNode((l1.val+l2.val)%10)
            tag = 1
        else:
            l3 = ListNode(l1.val+l2.val)
            tag = 0
        l3_copy = l3
        l1next = ListNode(0) if l1.next==None else l1.next
        l2next = ListNode(0) if l2.next==None else l2.next
        if l1.next==None and l2.next==None and tag ==1:
            l3_copy.next = ListNode(1)
        if not(l1.next==None and l2.next==None):
            while 1:
                if tag == 1:
                    if l1next.val+l2next.val+1>9:
                        l3_copy.next = ListNode((l1next.val+l2next.val+1)%10)
                        tag = 1
                    else:
                        l3_copy.next = ListNode(l1next.val+l2next.val+1)
                        tag = 0
                else:
                    if l1next.val+l2next.val>9:
                        l3_copy.next = ListNode((l1next.val+l2next.val)%10)
                        tag = 1
                    else:
                        l3_copy.next = ListNode(l1next.val+l2next.val)
                        tag = 0
                l3_copy = l3_copy.next        
                if l1next.next==None and l2next.next==None:
                    if tag == 1:
                        l3_copy.next = ListNode(1)
                    break;        
                l1next = ListNode(0) if l1next.next==None else l1next.next
                l2next = ListNode(0) if l2next.next==None else l2next.next   
        return l3   

 

这里需要说明一下leetcode给出的ListNode类型的操作方式:

idx = ListNode(3)
n = idx
n.next = ListNode(4)
n = n.next
n.next = ListNode(5)
n = n.next
return idx
# idx[3,4,5]

 

2、Add Two Numbers