[英]Finding the kth to the last element of a linked list
I was trying to implement this recursively, but I'm not sure why this code doesn't work (this is assuming that I have a length function that returns correctly): 我试图递归地实现它,但是我不确定为什么这段代码不起作用(这是假设我有一个正确返回的length函数):
Node findk(Node head, int k) {
if (node_length(head)==k) {
return head; }
else {
return findk(head.next, k-1);}}
Thanks! 谢谢!
There are two issues with your code: 您的代码有两个问题:
k
as you go down the list, and k
,并且 null
before reaching k
-th element when the list is too short. k
个元素之前先击null
。 Here is one possible fix: 这是一种可能的解决方法:
Node findk(Node head, int k) {
if (head == null) return null;
if (node_length(head)==k) return head;
return findk(head.next, k);
}
Note that this solution is O(n 2 ), because node_length
, which must be O(1), is called for each of Nk
nodes of the list. 请注意,此解决方案为O(n 2 ),因为对列表的
Nk
节点中的每个节点都调用了必须为O(1)的node_length
。 There are several ways of doing it faster - for example, by finding int m = node_length(head)
, and then returning (mk)
-th node from the beginning of the list. 有多种方法可以更快地完成此操作-例如,找到
int m = node_length(head)
,然后从列表的开头返回第(mk)
个节点。
If you want to find the K'th element from the end You are decrementing the value of K which is wrong, the correct code is as below : 如果要从头开始查找第K个元素,请减小K的值,该值是错误的,正确的代码如下:
Node findk(Node head, int k) {
if (node_length(head)==k) {
return head;
} else {
return findk(head.next, k);
}
}
Also I hope your node_length() method takes care of the scenario where the Node passed to it is null. 我也希望您的node_length()方法能够处理传递给它的Node为null的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.