- analysis
Double pointer, let one pointer go n steps first, then the fast pointer and slow pointer move backward at the same time, until the fast pointer moves to the end of the linked list.
- Code
/**
* 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;
}
};