-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTwoLinkedList
33 lines (25 loc) · 957 Bytes
/
addTwoLinkedList
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
# TC: O(max(m,n)) SC: O(max(m,n)) # Whichever list is larger
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def sumOfLinkedLists(linkedListOne, linkedListTwo):
# create head for new ll
newLLhead = LinkedList(0)
currNode = newLLhead
carry = 0
node1 = linkedListOne
node2 = linkedListTwo
while node1 is not None or node2 is not None or carry != 0:
val1 = node1.value if node1 is not None else 0
val2 = node2.value if node2 is not None else 0
sumofvalues = val1+val2+carry
newValue = sumofvalues % 10
newNode = LinkedList(newValue)
currNode.next = newNode
currNode = newNode
carry = sumofvalues // 10
node1 = node1.next if node1 is not None else None
node2 = node2.next if node2 is not None else None
return newLLhead.next