实现单向链表的查找节点函数

Implementing a find node function for singly linked list

我需要为 python 中的单链表创建一个查找节点函数。

Find:这个方法接受一个值作为参数,returns 是包含这个值的第一个节点的索引。如果没有发现包含该值的节点,return False

到目前为止我有:

class Node:
  def __init__(self, dataval=None):
    self.dataval = dataval
    self.nextval = None

class LinkedList:
  def __init__(self):
    self.headval = None
  def __str__(self):
    node = self.headval
    output = "[ "
    while(node != None):
      output = output + str(node.dataval) + ", "
      node = node.nextval
    if(len(output) > 2):
      output = output[:-2]
    return output + " ]"


  def find(self, val):
    current=self.headval 
    count=0
    while(current):
      if (count==val):
        return current
      count+=1
      current=current.nextval
    assert(False)
    return 0 

        

我没有得到正确的 output.Do 你知道它可能是什么吗?我知道这是因为我比较的是值而不是索引,但我该如何解决这个问题?

你说得对。您需要查看 dataval 而不是索引:

  def find(self, val):
    current=self.headval 
    count=0
    while current != None:
      if (current.dataval==val):
        return count
      count+=1
      current=current.nextval
    assert(False)
    return -1      # return -1 instead of 0