[英]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.