Py学习  »  Python

如何从链接列表中找到第一个索引,其中使用Python中的递归找到特定的值

L0KiZ • 5 年前 • 1435 次点击  

class Linkedlist:

    def __init__(self, value, tail):
        self.value = value
        self.tail = tail

在这之后,还有其他方法可以很好地工作,但问题是如何返回链接列表中的第一个索引,其中的值是x?我试过下一个,但它只对第一个索引(0)有效。

   def index(self, x):

        index = 0
        if x == self.value:
            return 0
        else:
            return Linkedlist.index(self.tail, index+1)

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53824
 
1435 次点击  
文章 [ 2 ]  |  最新文章 5 年前
blueteeth
Reply   •   1 楼
blueteeth    5 年前

index() 需要接受你正在寻找的价值( x )以及最初为0的当前索引。

我的假设是:

  • value 是链接列表的标题。
  • tail
  • 如果没有下学期, 没有。
class LinkedList:
    def __init__(self, value, tail):
        self.value = value
        self.tail = tail

    def index(self, x, i=0):
        if self.value == x:
             return i
        if self.tail is None:
             raise IndexError
        return self.tail.index(x, i+1)
Heap Overflow
Reply   •   2 楼
Heap Overflow    5 年前

不需要传递索引。如果值就在这里,则返回0。否则获取尾部的索引并添加1。

def index(self, x):
    if x == self.value:
        return 0
    return self.tail.index(x) + 1