HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Adding 2 linked lists

Submitted by: @import:stackexchange-codereview··
0
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: 7 -> 5 -> 6 = 756

I 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 total

Solution

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:

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 total


Simplify

The logic can be simplified, a lot:

def sumlist(ll):
    total = 0
    while ll:
        total *= 10
        total += ll.data
        ll = ll.next
    return total


I also simplified the None comparison, instead of if ll != None you can write simply if ll

Naming

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 total
def sumlist(ll):
    total = 0
    while ll:
        total *= 10
        total += ll.data
        ll = ll.next
    return total

Context

StackExchange Code Review Q#51258, answer score: 4

Revisions (0)

No revisions yet.