leetcode 2. 兩數相加

給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,而且它們的每一個節點只能存儲 一位 數字。spa

若是,咱們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。code

您能夠假設除了數字 0 以外,這兩個數都不會以 0 開頭。對象

示例:blog

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
緣由:342 + 465 = 807

Python 鏈表,下一個節點直接指向對象。it

# 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
        """
        re = ListNode(0)
        r = re
        carry = 0
        while l1 or l2:
            x1 = l1.val if l1 else 0
            x2 = l2.val if l2 else 0
            s = x1 + x2 + carry
            carry = s // 10
            r.next = ListNode(s%10)
            r = r.next
            if l1!=None: l1 = l1.next
            if l2!=None: l2 = l2.next

        if carry > 0:
            r.next = ListNode(1)

        return re.next



a = ListNode(2)
a.next = ListNode(4)
a.next.next = ListNode(3)

b = ListNode(5)
b.next = ListNode(6)
b.next.next= ListNode(4)

main = Solution()
ans = main.addTwoNumbers(a,b)

while ans:
    print(ans.val,end='')
    ans = ans.next
相關文章
相關標籤/搜索