【发布时间】:2018-03-30 13:23:51
【问题描述】:
我在 python 中有一个简单的 LinkedList 实现。如何在方法中使用递归?我知道递归是如何工作的,但我如何在递归中使用 self 。如果有人可以修复我的代码,那就太好了,但我对解释更感兴趣,所以我可以在不同的方法中使用它。
链表代码:
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时循环更有效。 -
您似乎误解了
self的用途。在不分析您的代码的情况下:return 1 + count(ptr.next)做了什么?为什么在一种情况下返回一个字符串 0 而在另一种情况下返回一个数字 1... -
注意python中有一个recursion limit,所以你的列表不能超过这个,否则你的递归计数方法会崩溃!
-
@Blorgbeard 不幸的是,我不得不为此使用递归。
标签: python recursion linked-list