简体   繁体   English

如何递归打印链表

[英]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 :如果它是元素的链接列表,则可以将参数添加到list function 中,这是从中获取数据的位置, None值默认为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:请注意,除非f.data是一个列表,否则您可能应该返回一个,即替换:

    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 定义:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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