我有一个python的LinkedList的简单实现。如何在方法内使用递归?我知道递归如何工作,但我如何使用递归自我。如果有人可以修复我的代码,但我对解释更感兴趣,所以我可以以不同的方法使用它。在python递归LinkedLists
的LinkedList代码:
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
self.head = Node(item, self.head)
def remove(self):
if self.is_empty():
return None
else:
item = self.head.item
self.head = self.head.next
return item
def is_empty(self):
return self.head == None
我的代码是:
def count(self, ptr=self.head):
if ptr == None:
return '0'
else:
return 1 + self.count(ptr.next)
它给了我一个错误:
def count(self, ptr=self.head):
NameError: name 'self' is not defined
任何帮助深表感谢。
我不会为此推荐使用递归。更新'ptr = ptr.next'并循环,而不是'None'更有效。 – Blorgbeard
看来你误解了'''self'''用于什么。不分析你的代码:'''返回1 + count(ptr.next)'''做什么?为什么在一种情况下返回0的字符串,另一种情况是1的数字... – sascha
请注意,有一个[递归限制](https://stackoverflow.com/questions/3323001/what-is-the-maximum Python中的递归深度 - 在python中,以及如何增加它),所以你的列表不能超过这个长度,否则你的递归计数方法会崩溃! – Blorgbeard