- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd_two_numbers.py
44 lines (37 loc) · 1.35 KB
/
add_two_numbers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
classSolution:
defaddTwoNumbers(self, l1: ListNode, l2: ListNode) ->ListNode:
# important: always point to the head (virtual node)
dummy_head=ListNode(None)
# current -> dummy_head
current=dummy_head
overflow=0
# be careful: the while loop uses 'or'
while (l1!=None) or (l2!=None):
# if one list is longer than another
# create the '0' ListNode
ifl1==None:
l1=ListNode(0)
ifl2==None:
l2=ListNode(0)
# handle the overflow problem
my_sum=l1.val+l2.val+overflow
ifmy_sum>=10:
my_sum=my_sum-10
overflow=1
else:
overflow=0
# move the pointers
current.next=ListNode(my_sum)
current=current.next
l1=l1.next
l2=l2.next
# the edge case
ifoverflow==1:
current.next=ListNode(1)
# return the linked list
returndummy_head.next