Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 在Python 2.7中,如何正确地递归打印链表?_Python 2.7_Recursion_Linked List - Fatal编程技术网

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这样做。