class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
if (head == null || k <= 0) {
return null;
}
ListNode pos1 = head, pos2 = head;
for (int i = 0; i < k - 1; i++) {
if (pos1.next == null) {
return null;
}
pos1 = pos1.next;
}
while (pos1.next != null) {
pos1 = pos1.next;
pos2 = pos2.next;
}
return pos2;
}
}
评论