class Node:
def __init__(self,data):
self.data=data
self.next=None
def traversal(head):
current = head
while current is not None:
print(current.data)
current = current.next
print("End")
这是正常的节点打印功能。 如何将遍历函数转换为使用递归来打印节点?
答案 0 :(得分:1)
通常,递归在开头有一个退出检查
def traversal(node):
if node is None:
print("End")
return
print(node.data)
traversal(node.next)
答案 1 :(得分:0)
这样的事情:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def traversal(head):
current = head
if current is not None:
print(current.data)
traversal(current.next)
else:
print("End")