算法1
快慢指针
用上快慢指针,你将拥有一切
Java 代码
class Solution {
public ListNode findKthToTail(ListNode head, int k) {
if(head==null||k>ListNodeLong(head))
return null;
ListNode fast = head;
ListNode slow = head;
int i = 0;
while(i<k&&fast!=null){
fast = fast.next;
i++;
}
while(fast!=null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
public int ListNodeLong(ListNode head){
int count = 0;
ListNode node = head;
while(node!=null){
node = node.next;
count++;
}
return count;
}
}