快慢指针。
/**
* 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) {
if(head == nullptr || k == 0) return nullptr;
ListNode *fast = head, *slow = head;
for (int i = 0; i < k - 1; i++) {
if (fast->next == nullptr)
return nullptr;
else
fast = fast->next;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};