快慢指針
快指針線遍歷到第k-1個數,然後慢指針在從頭開始遍歷,這樣快慢指針有k-1個間隔,當快指針到鏈表末尾時,慢指針指的數就是倒數第k個數。
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null||k==0){
return null;
}
ListNode pHead=head;
for(int i=0;i<k-1;i++){
if(pHead.next!=null){
pHead=pHead.next;
}
else{
return null;
}
}
ListNode pSlow=head;
while(pHead.next!=null){
pHead=pHead.next;
pSlow=pSlow.next;
}
return pSlow;
}
}