patternpythonMinor
Adding 2 linked lists
Viewed 0 times
linkedaddinglists
Problem
The problem I have is to find the sum of 2 linked lists. Each linked list node contains 1 digit that represents a number.
My algorithm works but I was wondering if there is a more efficient (speed and memory wise) to solve this problem OR maybe some minor tweaks I can do to reduce space and runtime.
Example:
I am trying to find the sum of 2 linked lists.
My algorithm works but I was wondering if there is a more efficient (speed and memory wise) to solve this problem OR maybe some minor tweaks I can do to reduce space and runtime.
Example:
7 -> 5 -> 6 = 756I am trying to find the sum of 2 linked lists.
def addlist(LL1, LL2):
storage = []
multiplier = 1
total = 0
while LL1 != None:
storage.append(LL1.data)
LL1 = LL1.next
for i in storage[::-1]:
total += i*multiplier
multiplier *= 10
storage = []
multiplier = 1
while LL2 != None:
storage.append(LL2.data)
LL2 = LL2.next
for j in storage[::-1]:
total += j*multiplier
multiplier *= 10
return totalSolution
Don't repeat yourself
Your method has the same code duplicated twice in it. You should always try to eliminate this kind of duplication, for example like this:
Simplify
The logic can be simplified, a lot:
I also simplified the
Naming
The convention is to use lowercase variable names, so it would be better to change
Your method has the same code duplicated twice in it. You should always try to eliminate this kind of duplication, for example like this:
def addlists(LL1, LL2):
return sumlist(LL1) + sumlist(LL2)
def sumlist(LL1):
storage = []
multiplier = 1
total = 0
while LL1 != None:
storage.append(LL1.data)
LL1 = LL1.next
for i in storage[::-1]:
total += i*multiplier
multiplier *= 10
return totalSimplify
The logic can be simplified, a lot:
def sumlist(ll):
total = 0
while ll:
total *= 10
total += ll.data
ll = ll.next
return totalI also simplified the
None comparison, instead of if ll != None you can write simply if llNaming
The convention is to use lowercase variable names, so it would be better to change
LL1 and LL2.Code Snippets
def addlists(LL1, LL2):
return sumlist(LL1) + sumlist(LL2)
def sumlist(LL1):
storage = []
multiplier = 1
total = 0
while LL1 != None:
storage.append(LL1.data)
LL1 = LL1.next
for i in storage[::-1]:
total += i*multiplier
multiplier *= 10
return totaldef sumlist(ll):
total = 0
while ll:
total *= 10
total += ll.data
ll = ll.next
return totalContext
StackExchange Code Review Q#51258, answer score: 4
Revisions (0)
No revisions yet.