@@ -26,39 +26,32 @@ def __init__(self, val=0, next=None):
26
26
self .next = next
27
27
class Solution :
28
28
def addTwoNumbers (self , l1 : ListNode , l2 : ListNode ) -> ListNode :
29
- res = ListNode (0 )
30
- tempres = res
31
- flag = 0
32
- carry = 0
33
- while l1 != None and l2 != None :
34
- if flag == 0 :
35
- temp = l1 .val + l2 .val
36
- res .val = temp % 10
37
- carry = int (temp / 10 )
38
- flag += 1
39
- else :
40
- temp = l1 .val + l2 .val + carry
41
- tempres .next = ListNode (temp % 10 )
42
- tempres = tempres .next
43
- carry = int (temp / 10 )
29
+ temp = l1 .val + l2 .val
30
+ count = temp // 10
31
+ res = ListNode (temp % 10 )
32
+ cur = res
33
+ while l1 .next and l2 .next :
34
+ l1 , l2 = l1 .next , l2 .next
35
+ temp = l1 .val + l2 .val + count
36
+ count = temp // 10
37
+ cur .next = ListNode (temp % 10 )
38
+ cur = cur .next
39
+ while l1 .next :
44
40
l1 = l1 .next
41
+ temp = l1 .val + count
42
+ count = temp // 10
43
+ cur .next = ListNode (temp % 10 )
44
+ cur = cur .next
45
+ while l2 .next :
45
46
l2 = l2 .next
46
- while l1 :
47
- temp = l1 .val + carry
48
- tempres .next = ListNode (temp % 10 )
49
- tempres = tempres .next
50
- carry = int (temp / 10 )
51
- l1 = l1 .next
52
- while l2 :
53
- temp = l2 .val + carry
54
- tempres .next = ListNode (temp % 10 )
55
- tempres = tempres .next
56
- carry = int (temp / 10 )
57
- l2 = l2 .next
58
- if carry != 0 :
59
- tempres .next = ListNode (1 )
47
+ temp = l2 .val + count
48
+ count = temp // 10
49
+ cur .next = ListNode (temp % 10 )
50
+ cur = cur .next
51
+ if count : cur .next = ListNode (count )
60
52
return res
61
53
62
- # mat = Solution()
63
-
64
-
54
+ """
55
+ 时间复杂度:$O(max(m, n)$ # m, n 分别 l1 和 l2 的长度
56
+ 空间复杂度:$O(max(m, n))$
57
+ """
0 commit comments