Question type: double pointer
The idea is that the two pointers are separated by k. When the latter pointer reaches the end, the previous pointer is the correct answer.
topic
Input a linked list, output the k-th penultimate in the linked list
a node.
Notice:
k >= 1;
如果 k
大于链表长度,则返回 NULL;
Sample
Input: linked list: 1->2->3->4->5, k=2
output: 4
java code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode findKthToTail(ListNode pListHead, int k) {
if (pListHead == null) return null;
ListNode pre = pListHead;
ListNode last = pListHead;
for (int i = 1; i < k; i++) {
if (last.next == null) return null;
last = last.next;
}
while (last.next != null) {
last = last.next;
pre = pre.next;
}
return pre;
}
}