-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_linkedListSummation.py
54 lines (44 loc) · 1.24 KB
/
2_linkedListSummation.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
45
46
47
48
49
50
51
52
53
54
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1, l2):
sum = carry = 0
l3Head = ListNode()
temp3 = l3Head
temp1 = l1
temp2 = l2
while temp1 and temp2:
sum = temp1.val + temp2.val + carry
carry = sum //10
temp3.next = ListNode(sum%10)
temp1,temp2,temp3 = temp1.next,temp2.next,temp3.next
l3 = temp1 if temp1 else temp2
while l3:
sum = l3.val + carry
carry = sum //10
temp3.next = ListNode(sum%10)
l3,temp3 = l3.next,temp3.next
if carry >0:
temp3.next = ListNode(carry)
return l3Head.next
# Initializing Nodes
l1 = ListNode(9)
l1.next = ListNode(9)
l1.next.next = ListNode(9)
l1.next.next.next = ListNode(9)
l1.next.next.next.next = ListNode(9)
l1.next.next.next.next = ListNode(9)
l1.next.next.next.next.next = ListNode(9)
l2 = ListNode(9)
l2.next = ListNode(9)
l2.next.next = ListNode(9)
l2.next.next.next = ListNode(9)
# Testing Function
sol = Solution()
summ = sol.addTwoNumbers(l1,l2)
while summ:
print(summ.val,end = " ")
summ = summ.next
print()