剑指 Offer 22. 链表中倒数第k个节点
快慢指针。
/**
* 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;
}
};