Hackbright Code Challenges

Add Linked Lists

Add Linked Lists

Challenge

Harder

Concepts

Linked Lists

Download

add-linked-lists.zip

Solution

Add Linked Lists: Solution


There is a simple Node class for a linked list:

class Node(object):
    """Linked list node."""

    def __init__(self, data, next=None):
        self.data = data
        self.next = next

    def as_rev_string(self):
        """Represent data for this node and its successors as a string.

        >>> l1 = Node(3)
        >>> l1.as_rev_string()
        '3'

        >>> l1 = Node(3, Node(2, Node(1)))
        >>> l1.as_rev_string()
        '123'
        """

        out = []
        n = self

        while n:
            out.append(str(n.data))
            n = n.next

        return "".join(reversed(out))

This includes a useful function for printing the contents of the list in reverse order. For example, if given a list of 3 → 2 → 1:

>>> l1 = Node(3, Node(2, Node(1)))
>>> l1.as_rev_string()
'123'

You will be given two linked lists in “reverse-digit” format. For example, the number 123 would be given to you like this:

digraph ll1 { rankdir=LR d3 -> d2 -> d1 -> None; d1 [label="1"]; d2 [label="2"]; d3 [label="3"]; None [shape="none"]; }

And the number 456 like this:

digraph ll2 { rankdir=LR d3 -> d2 -> d1 -> None; d1 [label="4"]; d2 [label="5"]; d3 [label="6"]; None [shape="none"]; }

You should sum up these numbers You should return the sum of these two numbers in the same “reverse-digit” format.

For 123 + 456, this should return 579, in the form of a list like this:

digraph ll3 { rankdir=LR d3 -> d2 -> d1 -> None; d1 [label="5"]; d2 [label="7"]; d3 [label="9"]; None [shape="none"]; }

We’ve provided addll.py, with a function with a docstring:

def add_linked_lists(l1, l2):
    """Given two linked lists, treat like numbers and add together.

    l1: the head node of a linked list in "reverse-digit" format
    l2: the head node of another "reverse-digit" format

    Returns: head node of linked list of sum in "reverse-digit" format.
    """

However, it’s not implemented, so you get test failures when you run it.