递归实现LinkedList转普通列表函数返回None问题排查
问题原因及修复方案
核心问题
你的递归函数在非终止条件的分支里,没有返回递归调用的结果。
当递归走到最后一层(current.next is None),函数会返回填充好的result,但上层的函数调用只是执行了self.to_plain_list(current.next, result),并没有把这个返回值传递回去,所以上层函数执行完这行代码后没有任何返回,最终整个函数默认返回None。
修复代码
只需要在递归调用的那一行加上return即可:
def to_plain_list(self, current=None, result=None): """ Returns a regular Python list containing the same values, in the same order, as the linked list using recursion without loops """ if result is None: result = [] if current is None: current = self._head # 注意:这里应该append节点的值而不是Node对象,比如current.value(根据你的Node类定义调整) result.append(current.value) if current.next is None: return result # 加上return,把递归调用的结果传递回去 return self.to_plain_list(current.next, result)
额外提示
你现在的代码里result.append(current)添加的是Node对象实例,不是节点存储的数值(比如你添加的10、20这些),所以最终列表里会是一堆<__main__.Node object...>,建议改成result.append(current.value)(如果你的Node类用value属性存数据的话,根据实际属性名调整)。
内容的提问来源于stack exchange,提问作者Xave
相关产品推荐
相关产品推荐

