Link Length

Write a function in Python that returns the length (aka number of elements) of a well-formed (aka non-deep) linked list link.

def link-length(link):
    """    
    >>>link-length(Link(1, Link(2, Link(3, Link(4)))))
    4
    """

    # Your Code Here
Toggle Solution
def link-length(link):
    if link is Link.empty:
        return 0
    return link-length(link.rest) + 1

First, we should set up our recursive case. Since each element of the list has a length of 1, the length of a link should just be each 1 representing each element added together. We can achieve this by returning 1 plus the length of the rest of the link.

But now, we need to think of what happens when we get to the end of link, or if Link.empty is parsed in. In that case, there's nothing more in the rest of the list, so we can just return 0. Therefore, in the end, Link(1, Link(2, Link(3, Link(4)))) would be calculated as 1 + 1 + 1 + 1 + 0 = 4, which is the length of our linked list.

Now that you're done with this problem, why not give Deep Link Length a go?

results matching ""

    No results matching ""