最直观的想法是遍历两遍。
再者的想法是使用栈这种方式。
代码精简的角度是用两个指针,相隔k-1个位置并行。
最后一种方式的代码如下:
public ListNode find (ListNode node, int k) {
if (node == null)
return null;
int sum = 0;
ListNode tmp = node;
ListNode tmp1 = node;
while (tmp.next != null) {
if (sum++ < k)
tmp = tmp.next;
else {
tmp = tmp.next;
tmp1 = tmp1.next;
}
}
if (sum < k)
return null;
return tmp1;
}