Skip to content

Commit 587a785

Browse files
committed
Time: 7 ms (43.78%), Space: 17.8 MB (57.75%) - LeetHub
1 parent 6362852 commit 587a785

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# time complexity: O(m+n)
2+
# space complexity: O(m+n)
3+
from typing import Optional
4+
5+
6+
7+
8+
9+
class Solution:
10+
def reverseList(self, node: Optional[ListNode]) -> Optional[ListNode]:
11+
prev = None
12+
while node:
13+
nextNode = node.next
14+
node.next = prev
15+
prev = node
16+
node = nextNode
17+
return prev
18+
19+
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
20+
r1 = self.reverseList(l1)
21+
r2 = self.reverseList(l2)
22+
23+
totalSum = 0
24+
carry = 0
25+
result = ListNode()
26+
while r1 or r2:
27+
if r1:
28+
totalSum += r1.val
29+
r1 = r1.next
30+
if r2:
31+
totalSum += r2.val
32+
r2 = r2.next
33+
34+
result.val = totalSum % 10
35+
carry = totalSum // 10
36+
head = ListNode(carry)
37+
head.next = result
38+
result = head
39+
totalSum = carry
40+
41+
return result.next if carry == 0 else result

0 commit comments

Comments
 (0)