简体   繁体   中英

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!

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 ie 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM