这是链表中递归搜索功能的正确实现吗?
Is this the correct implementation of a recursive search function in a Linked List?
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)
我觉得将头部重置为 head.next 不太正确。如果不是,我的递归函数如何移动到下一个节点?
重置head肯定是错误的,这样你的链表就会丢失。对于第一次调用搜索,您需要指定从哪里开始,然后指定接下来要检查的节点(如果有的话):
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)
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)
我觉得将头部重置为 head.next 不太正确。如果不是,我的递归函数如何移动到下一个节点?
重置head肯定是错误的,这样你的链表就会丢失。对于第一次调用搜索,您需要指定从哪里开始,然后指定接下来要检查的节点(如果有的话):
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)