Python 这是链表中递归搜索函数的正确实现吗?
我有一种感觉,重新设置head-to-head.next不太正确。如果不是,我的递归函数如何移动到下一个节点?重置head肯定是错误的,这样会丢失链接列表。对于搜索的第一个调用,您需要指定从何处开始,然后检查下一个节点(如果有):Python 这是链表中递归搜索函数的正确实现吗?,python,recursion,data-structures,linked-list,Python,Recursion,Data Structures,Linked List,我有一种感觉,重新设置head-to-head.next不太正确。如果不是,我的递归函数如何移动到下一个节点?重置head肯定是错误的,这样会丢失链接列表。对于搜索的第一个调用,您需要指定从何处开始,然后检查下一个节点(如果有): 我不太明白下一个_节点是如何传递给else语句的?您能进一步解释一下吗?搜索方法的第二个参数是要检查的下一个节点,即head.next、head.next.next、head.next.next,依此类推。当您从类外调用search时,next_node为none,这
我不太明白下一个_节点是如何传递给else语句的?您能进一步解释一下吗?搜索方法的第二个参数是要检查的下一个节点,即head.next、head.next.next、head.next.next,依此类推。当您从类外调用search时,next_node为none,这是您需要将其设置为head的信号。顺便说一句,直接比较节点可能不起作用,您需要
if-next\u-node.data==node.data:return-next\u-node
我应该添加,在第一个if块中,next\u-node有效地创建了一个新变量,但由于python的作用域规则,它在方法体中是可见的,创建next_node变量,然后作为参数传递给搜索函数?next_node基本上创建两次,首先作为搜索方法的参数。如果此参数的值为None(在第一次调用search时),则将使用head值重新创建它。
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, head=None):
self.head = head
def insert(self, node):
if not self.head:
self.head = node
else:
node.next = self.head
self.head = node
def search(self, node):
if self.head == node:
return self.head
else:
if self.head.next:
self.head = self.head.next
return self.search(node)
def search(self, node, next_node=None):
if next_node is None:
next_node = self.head
if next_node == node:
return next_node
elif next_node.next is None:
return None
else:
return self.search(node, next_node.next)