1. 程式人生 > >leetcode 鏈表 兩數相加

leetcode 鏈表 兩數相加

相加 ddt con rap quest list onu 單個 clas

兩數相加

給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。

你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。

示例:

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

 1 # Definition for singly-linked list.
 2 class ListNode:
 3     def __init__(self, x):
 4         self.val = x
5 self.next = None 6 7 8 class Solution: 9 def addTwoNumbers(self, l1, l2): 10 """ 11 :type l1: ListNode 12 :type l2: ListNode 13 :rtype: ListNode 14 """ 15 head = ListNode(0) 16 cur = head 17 m = 0 18 while True:
19 if l1 is not None: 20 a = l1.val 21 else: 22 a = 0 23 if l2 is not None: 24 b = l2.val 25 else: 26 b = 0 27 if l1 is None and l2 is None and m == 0: 28 return head.next
29 else: 30 add = a + b + m 31 cur.next = ListNode(add % 10) 32 m = (a+b+m) // 10 33 cur = cur.next 34 if l1 is not None: 35 l1 = l1.next 36 if l2 is not None: 37 l2 = l2.next

leetcode 鏈表 兩數相加