Search code examples
pythonlinked-listnodes

how do I recursively find an element in a linked list but the last element is not equal to None


Im trying to find the last value on a linkedlist but the last node does not does not point to none. node 4 is not pointing to none so how do I find it recursively.

node1 = Node(44)
node2 = Node(220)
node3 = Node(320)
node4 = Node(402)
node2.setNext(node1)
node3.setNext(node2)
node4.setNext(node3)

so if I put in find the last value of node4 it should return 44


Solution

  • n = node1
    while n.next() == None:
        n = n.next()
     ... do something ...
    

    this while loop breaks when the last node is n so you can use n to refrence last node. Hope this helps :)

    Edit: If there is no node linked to node1 then it should return None when you run node1.next also i didn't quite understood the question if you want a recursive function of getting the last node here it is.

    def r(n: linkedlist)
        if n.next() == None:
            return n
        else:
            r(n.next())