[英]Cracking the Coding Interview, 6th Edition- Q: 2.2
問題是將第k個返回到單個鏈表的最后一個元素。 所有提議的解決方案都非常復雜,我不知道為什么我的解決方案無效。 有人可以讓我知道為什么嗎?
public class CrackTheInterview {
/**
* @param args the command line arguments
*/
public static Node kthToLast(Node n, int k) //pass in LinkedList's head node
{
int counter = 1;
while (n.next != null)
{
n = n.next;
}
//at the end of the while loop, n equals the last node in the LinkedList
while (counter != k)
{
n = n.previous;
counter++;
}
//now node n is the kth node from the end
return n;
}
}
class Node
{
Node next = null;
Node previous = null;
int data;
public Node (int d)
{
this.data = d;
}
}
單鏈表不會包含next
和previous
。 你有一個雙重鏈表,這顯然使這個問題更容易。
我沒有那本書的副本,所以我不知道它中可以找到哪些復雜的解決方案,但是下面的雙指解決方案對我來說似乎很簡單,並且除了使用單鏈表:
/* Returns the kth last node in the list starting at n.
* If the list is empty (n == null) returns null.
* If k is <= 1, returns the last node.
* If k is >= the number of nodes in the list, returns the first node.
*/
public static Node kthToLast(Node n, int k) {
Node advance = n;
while (--k > 0 && advance != null) {
advance = advance.next;
}
/* Now advance is k nodes forward of n. Step both in parallel. */
while (advance != null) {
advance = advance.next;
n = n.next;
}
return n;
}
書中的第一個解決方案是:
解決方案#1:如果鏈接列表大小已知
如果鏈接列表的大小是已知的,那么第k個到最后一個元素是(length-k)元素。 我們可以遍歷鏈表來找到這個元素。 因為這個解決方案非常簡單,我們幾乎可以肯定這不是面試官的意圖。
但是我們可以通過一次通過很容易地找到鏈表的大小! 所以修改OP的問題,我問下面的答案有什么問題?
我們使用兩個指針。 使用一個來查找鏈表的大小,並使用另一個去(大小 - k)步驟。
(在Python中實現)
def kth_to_last(head, k):
p1 = head
p2 = head
counter = 0
while p1.nxt is not None: # calculating the size of the linked list
p1 = p1.nxt
counter += 1
for _ in range(counter - k):
p2 = p2.nxt
return p2.val
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.