[英]Finding the kth to the last element of a linked list
我試圖遞歸地實現它,但是我不確定為什么這段代碼不起作用(這是假設我有一個正確返回的length函數):
Node findk(Node head, int k) {
if (node_length(head)==k) {
return head; }
else {
return findk(head.next, k-1);}}
謝謝!
您的代碼有兩個問題:
k
,並且 k
個元素之前先擊null
。 這是一種可能的解決方法:
Node findk(Node head, int k) {
if (head == null) return null;
if (node_length(head)==k) return head;
return findk(head.next, k);
}
請注意,此解決方案為O(n 2 ),因為對列表的Nk
節點中的每個節點都調用了必須為O(1)的node_length
。 有多種方法可以更快地完成此操作-例如,找到int m = node_length(head)
,然后從列表的開頭返回第(mk)
個節點。
如果要從頭開始查找第K個元素,請減小K的值,該值是錯誤的,正確的代碼如下:
Node findk(Node head, int k) {
if (node_length(head)==k) {
return head;
} else {
return findk(head.next, k);
}
}
我也希望您的node_length()方法能夠處理傳遞給它的Node為null的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.