Python 2.7 在Python 2.7中,如何正确地递归打印链表?
我一直试图递归地打印一个链表,但输出中不断出现错误 我编写了以下代码:Python 2.7 在Python 2.7中,如何正确地递归打印链表?,python-2.7,recursion,linked-list,Python 2.7,Recursion,Linked List,我一直试图递归地打印一个链表,但输出中不断出现错误 我编写了以下代码: def recursivePrint(linkedList): if linkedList == None: return print linkedList['data'], recursivePrint(linkedList['next']) 它的输出为: 2 7 1 3 10 None None None None None None None None 10 None 3 N
def recursivePrint(linkedList):
if linkedList == None:
return
print linkedList['data'], recursivePrint(linkedList['next'])
它的输出为:
2 7 1 3 10 None
None
None
None
None
None
None
None 10
None 3
None 1
None 7
None 2
我不知道我到底应该在这里做什么,因为这应该很容易做到。我还需要能够反向打印列表,我想我会做与我在第一个函数中所做的几乎相同的事情
我将此编码为反向:
def reversePrint(linkedList):
if linkedList == None:
return
print reversePrint(linkedList['next']), linkedList['data']
并得到了以下结果:
2 7 1 3 10 None
None
None
None
None
None
None
None 10
None 3
None 1
None 7
None 2
我认为if语句或递归步骤可能出了问题。我应该怎么做呢?您需要打印列表的头部,然后在尾部调用
recursivePrint
。现在的问题是,您正在打印recursivePrint
的返回值,它是None
def recursivePrint(linkedList):
if linkedList == None:
return
print linkedList['data']
recursivePrint(linkedList['next'])
您正在打印
recursivePrint
的返回值recursivePrint
返回None
。我假设要反向打印它,我必须在print语句之前调用reversePrint?@LamarrL Yes这样做。