leetcode 連結串列 兩數相加
阿新 • • 發佈:2018-12-30
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