rand_coder123
rand_coder123

Reputation: 11

How to print a linked list recursively

def list(self):
    if self.first.next == None:
        return self.first.data
    else:
        f = self.first.next
        return f.data + self.list()

Hi! This above is my code, the problem is that I dont know how to reduce the size of the linked list when calling upon it for the second time. Any idea how to avoid the maximum recursion depth?

THANKS!

Upvotes: 0

Views: 135

Answers (1)

Nick
Nick

Reputation: 147186

It's not clear exactly how you have implemented your linked list. If it is as a linked list of elements, you could add a parameter to your list function which is where to fetch the data from, with a None value defaulting to self.first:

def list(self, f = None):
    if f is None:
        f = self.first
    if f.next is None:
        return f.data
    else:
        return f.data + self.list(f.next)

Note that unless f.data is a list, you should probably return one instead i.e. replace:

    if f.next is None:
        return f.data
    else:
        return f.data + self.list(f.next)

with

    if f.next is None:
        return [f.data]
    else:
        return [f.data] + self.list(f.next)

Otherwise you will get addition rather than a list of values.

Here's a simple class definition demonstrating the code:

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

class LL:
    first = None
    
    def __init__(self, data = None):
        if data is not None:
            self.first = LLE(data)
            
    def add(self, data):
        if self.first is None:
            self.first = LLE(data)
            return
        f = self.first
        while f.next is not None:
            f = f.next
        f.next = LLE(data)
    
    def list(self, f = None):
        if f is None:
            f = self.first
        if f.next is None:
            return [f.data]
        else:
            return [f.data] + self.list(f.next)

l = LL(42)
l.list()
# [42]
l.add(57)
l.list()
# [42, 57]
l.add(55)
l.list()
# [42, 57, 55]

Upvotes: 1

Related Questions