[英]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.
节点4没有指向任何节点,所以我如何递归地找到它。
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 所以如果我输入找到node4的最后一个值,它应该返回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. 此外,您需要一个用于创建链接列表的类,例如
LinkedList
,该实例将具有指向第一个成员的指针。
You may implement this class with the method for setting this pointer, say setFirst()
; 您可以使用设置指针的方法来实现此类,例如
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); 或直接在构造函数中设置此指针(即在
__init__()
方法中);或者 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. 当最后一个节点为n时,该while循环中断,因此您可以使用n表示最后一个节点。 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. 编辑:如果没有链接到node1的节点,那么当您运行node1.next时,它应该返回None。我也不太了解这个问题,如果您想要递归函数来获取最后一个节点。
def r(n: linkedlist)
if n.next() == None:
return n
else:
r(n.next())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.