Add Two Numbers(from leetcode python 鏈表)

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

你能夠假設除了數字 0 以外,這兩個數字都不會以零開頭。指針

示例:code

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

  

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def addTwoNumbers(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         if l1 == None: return l2
15         if l2 == None: return l1
16         // 使用dummyHead指向頭結點,最後返回dummyHead.next
17         dummy_head = ListNode(0)
18         // 指針
19         pt = dummy_head
20         // 是否進位
21         carry = 0
22         while l1 and l2:
23             pt.next = ListNode((l1.val + l2.val + carry) % 10)
24             carry = (l1.val + l2.val + carry) / 10
25             pt = pt.next;
26             l1 = l1.next;
27             l2 = l2.next
28         if l1:
29             while l1:
30                 pt.next = ListNode((l1.val + carry) % 10)
31                 carry = (l1.val + carry) / 10
32                 pt = pt.next;
33                 l1 = l1.next
34             if carry == 1:
35                 pt.next = ListNode(1)
36             return dummy_head.next
37         if l2:
38             while l2:
39                 pt.next = ListNode((l2.val + carry) % 10)
40                 carry = (l2.val + carry) / 10
41                 pt = pt.next;
42                 l2 = l2.next
43             if carry == 1:
44                 pt.next = ListNode(1)
45             return dummy_head.next
46         if carry == 1:
47             pt.next = ListNode(1)
48         return dummy_head.next
相關文章
相關標籤/搜索