[英]Recursive Algorithm to find Kth last element in a linked list
我是 Java 的新手,我目前正在阅读“Cracking the Coding Interview”一书以及他们使用 Wrapper Class 在链表中查找第 k 个最后一个元素的方法。 我一直在查看代码,但不确定发生了什么。
class Index{
public int value = 0;
}
LinkedListNode kthToLast(LinkedListNode head, int k){
Index idx = new Index();
return kthToLast(head, k, idx);
LinkedListNode kthToLast(LinkedListNode head, int k, Index idx){
if(head == null){
return null;}
LinkedListNode node = kthToLast(head.next, k, idx);
idx.value = idx.value + 1;
if (idx.value == k){
return head;
}
return node;
}
有人可以解释这段代码中发生了什么吗? 这似乎很混乱。 另外,为什么有 2 个函数 kthToLast 传入的参数数量不同? (最初是 2 个参数,然后是 3 个参数)。
同样对于 kthToLast 的递归,我对LinkedListNode node = kthToLast(head.next, k, idx);
行之后的代码感到困惑。 将执行,因为它将递归调用自身,并且后续代码将在所有递归调用完成后的某个时间运行。
最后,为什么我们要返回 head return head
以及返回 node return node
?
如果有人能够解释这段代码中发生的事情的完整过程(以及为什么使用书中所述的 Wrapper Class),我将不胜感激。 谢谢!
链接列表可以用许多不同的方式表示。 一种更常见的方法是作为节点列表,其中每个节点通常至少有两件事:一些数据和另一个节点。
public class LinkedListNode
{
int data;
LinkedListNode next;
}
为了演示发生了什么,让我们使用这个链表示例,其中 Node2 是您的头节点,我们试图找到k=2
:
Node2 -> Node1 -> Node0
在第一个方法kthToLast(LinkedListNode head, int k)
:
kthToLast(LinkedListNode head, int k, Index idx)
用您的新索引调用从头节点开始,我们通过调用与head.next
相同的方法递归地遍历整个链表,直到“基本情况”变为真。 用 D# 表示深度,可以看成:
D1 - Node2 (head) is NOT null so we skip the if statement
D1 - LinkedListNode node = return value of (D2) recursive call
D2 - Node1 (head) is NOT null so we skip the if statement
D2 - LinkedListNode node = return value of (D3) recursive call
D3 - Node0 (head) is NOT null so we skip the if statement
D3 - LinkedListNode node = return value of (D4) recursive call
D4 - null (head) will return back to Depth 3
现在已经在第 4 个深度调用了 return 语句,我们将开始 go 通过先前的深度备份,直到我们到达第 k 个节点。
D3 - LinkedListNode node = null
D3 - idx.value = 0 + 1
D3 - 1 != 2 therefore, return node
D2 - LinkedListNode node = null
D2 - idx.value = 1 + 1
D2 - 2 == 2 therefore, return head (Node1)
D1 - LinkedListNode node = Node1
D1 - idx.value = 2 + 1
D1 - 2 != 1 therefore, return node
因此,返回了我们的 LinkedList (Node1) 中的第二个节点。 通过递归,它有助于跟踪每个深度的深度、值(和返回值),当然还有你的基本情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.