链表中倒数第k个节点(剑指offer-14)-LMLPHP

 /*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode P2 = head;//head其实就是P1节点,让P2和P1指向链表开头
while(k != 0){
if(P2 == null){//k超出链表长度,直接返回null
return null;
}
P2 = P2.next;
k--;
}
while(P2 != null){//同时移动P1和P2
P2 = P2.next;
head = head.next;
}
return head;
}
}
05-28 12:21