这是链接列表中递归搜索功能的正确实现吗?

时间:2015-02-10 02:43:06

标签: python recursion data-structures 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是不对的。如果不是,我的递归函数如何移动到下一个节点?

1 个答案:

答案 0 :(得分:0)

重置头肯定是错误的,你会以这种方式丢失你的链表。对于第一次搜索调用,您需要指定从哪里开始,然后指定下一个要检查的节点(如果有的话):

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)