微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为单链表实现查找节点功能

如何解决为单链表实现查找节点功能

我需要为python中的单链接列表创建一个find节点函数

查找:此方法一个值作为参数,并返回包含该值的第一个节点的索引。如果未找到包含该值的节点,则返回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 

        

我没有得到正确的输出。您知道可能是什么吗?我知道它是因为即时比较值而不是索引,但是我该如何解决呢?

解决方法

您是对的。您需要查看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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。