【问题标题】:Is this the correct implementation of a recursive search function in a Linked List?这是链接列表中递归搜索功能的正确实现吗?
【发布时间】:2015-02-10 02:43:05
【问题描述】:
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 to head.next 重置不太正确。如果不是,我的递归函数如何移动到下一个节点?

【问题讨论】:

    标签: python recursion data-structures linked-list


    【解决方案1】:

    reset 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)
    

    【讨论】:

    • 我不太明白 next_node 是如何传递给 else 语句的?你能进一步解释一下吗?
    • search 方法的第二个参数是要检查的下一个节点,即 head.next、head.next.next、head.next.next 等。当您从类外部调用 search 时,next_node 为 none,这是您需要将其设置为 head 的信号。 BTW,直接比较节点可能行不通,你需要if next_node.data == node.data: return next_node
    • 我应该在第一个 if 块中添加 next_node 有效地创建了一个新变量,但是由于 python 范围规则,它在方法的主体中是可见的。
    • 那么在第一个 if 块中,创建 next_node 变量,然后作为参数传递给搜索函数?
    • next_node 本质上被创建了两次,第一次作为搜索方法的参数。如果此参数的值为 None (在第一次调用搜索时),则使用 head 的值重新创建它。
    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多