- análisis
Puntero doble, deje que un puntero avance n pasos primero, luego el puntero rápido y el puntero lento se mueven hacia atrás al mismo tiempo, hasta que el puntero rápido se mueva al final de la lista vinculada.
- Código
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode* fast = head;
while(k > 0 && fast != nullptr){
fast = fast -> next;
k--;
}
ListNode* slow = head;
while(fast != nullptr){
fast = fast -> next;
slow = slow -> next;
}
return slow;
}
};