剑指 Offer 22 链表中倒数第k个节点
概述
https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
快慢指针法
要注意,虽然本题没挖坑,但是我们要注意以下几点:
- k 为无符号整型时,uint(0) - 1 将导致溢出。
- 我们在用 next 属性时务必检查是否是 nullptr,本题由于指明了必定存在所以我们就没检查。
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
auto dummy = new ListNode;
dummy->next = head;
auto fast = dummy, slow = dummy;
k --;
while (k --) fast = fast->next;
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};
Links: sword-offer-22