【发布时间】:2015-09-08 21:54:13
【问题描述】:
问题是将第 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;
}
}
【问题讨论】:
-
除了答案中指出的问题之外,问题陈述似乎不完整,因为它没有指定如果列表少于
k节点会发生什么。您的代码也没有考虑到这种可能性。 -
好吧,你的
Node类不遵守问题描述。问题表明您有一个singly-linked list,并且您的节点同时有一个previous和一个next。我猜这就是solution is invalid的意思?
标签: java algorithm linked-list