简体   繁体   中英

How to find the first index from the linked list, where the certain value is found using recursion in Python

I have a basic singly linked list and I try to find the first index from the linked list, where the certain value is found using recursion. I have initialized the linked list in this way:

class Linkedlist:

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

After this there are other methods that work fine, but the problem is how I can return the first index in the linked list, where the value x is found? I have tried the next one, but it only works for the first index (0).

   def index(self, x):

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

I think the problem is that the index stays always zero. How I can work around this?

index() needs to take the value you're looking for ( x ) and also the current index which is initially 0.

Assumptions I'm making:

  • value is the head of the linked list.
  • tail is a linked list.
  • If there is no next term, tail is None.
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)

No need for passing an index. If the value is right here, return 0. Otherwise get the index in the tail and add 1.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM