我正在通过唐尼的如何像计算机科学家一样思考,我对Linked List有一个关于他的print_backward()函数的问题。此功能为什么向后打印链接列表?
首先,这里唐尼在Python实现链表:
class Node:
#initialize with cargo (stores the value of the node)
#and the link. These are set to None initially.
def __init__(self, cargo = None, next = None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
我们给这个类中的下列货物和链接值:
#cargo
node1 = Node('a')
node2 = Node('b')
node3 = Node('c')
#link them
node1.next = node2
node2.next = node3
要打印的链表,我们用另一种唐尼的职能。
def printList(node):
while node:
print node,
node = node.next
>>>printList(node1)
>>>a b c
所有非常简单。但我不明白如何在以下函数中的递归调用允许向后打印链表。
def print_backward(list):
if list == None : return
print_backward(list.next)
print list,
>>>print_backward(node1)
>>>c b a
不会调用“list.next”作为print_backward的值只是给你“b c”?
注意:下面几个人指出,这个函数设计的很糟糕,因为给定任何列表,我们不能表明它总是会达到基本情况。唐尼在同一章的后面也指出了这个问题。
正如其他答案所指出的那样,这个函数是递归的说明,但是也有一些缺陷:不是尾递归(会在长列表上导致堆栈溢出错误),类节点应该从'object'继承,'' list'不应该被用作变量名称。 – jrouquie 2012-07-19 21:26:00