简体   繁体   中英

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

Your linked list looks like this:

node4 -> node3 -> node2 -> node1

No start, no end, your linked list is in a vacuum.

Correct it to it will look like,

linked_list -> node4 -> node3 -> node2 -> node1 -> None

So, you need to add the command

node1.setNext(None)

Moreover, you need a class for creating linked lists, say LinkedList , which instances will have a pointer to the first member.

You may implement this class with the method for setting this pointer, say setFirst() ; then you will use these commands:

my_list = LinkedList()
my_list.setFirst(node4)

or set this pointer directly in the constructor (ie in the __init__() method); then you will use this command:

my_list = LinkedList(node4)
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())

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