-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddTwoNumbers.py
43 lines (37 loc) · 991 Bytes
/
AddTwoNumbers.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
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def addTwoNumers(l1, l2):
current = 0
carry = 0
rList = None
while l1 or l2 or carry != 0:
current += carry
if l1:
current += l1.val
l1 = l1.next
if l2:
current += l2.val
l2 = l2.next
carry = current // 10
current = current % 10
if rList is None:
rList = ListNode(current)
head = rList
else:
rList.next = ListNode(current)
rList = rList.next
current = 0
return head
if __name__ == "__main__":
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
newListNode = addTwoNumers(l1, l2)
while newListNode:
print(newListNode.val, end=" ")
newListNode = newListNode.next