题目
输入一个链表,输出该链表中倒数第k个结点。

思路
使用快慢指针(双指针),让快指针先走k步,然后快慢指针一起移动,当快指针走到末尾时,慢指针正好指向倒数第k个节点。

code
java
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null) return null;//head为空
if(k<=0) return null;//k不合法
ListNode fast=head;
ListNode slow=head;
int count=0;
while(count!=k){
if(fast!=null){
fast=fast.next;
count++;
}else{
return null;//k超出链表的个数
}
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}