public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static ListNode FindKthToTail(ListNode head, int k) {
if(head == null){
return null;
}
ListNode p1 = head;
while(p1 != null && k-- > 0){
p1 = p1.next;
}
if(k > 0){
return null;
}
ListNode p2 = head;
while(p1 != null){
p1 = p1.next;
p2 = p2.next;
}
return p2;
}
解题思路:
利用第二个指针记录第一个指针从第k个位置走完的位置,
第二个指针走完n-k个位置,此时第二个指针的位置就是倒数第二个位置