/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int k) {
        // write code here
        ListNode* pre = pHead;
        ListNode* cur = pHead;

        // 判断k值是否大于链表长度.
        for (int i = 1; i <= k; ++i) {
            if (cur == nullptr)
                return nullptr;
            cur = cur->next;
        }
        
        // k值刚好等于链表长度.
        if (cur == nullptr)
            return pHead;
        
        while (cur->next) {
            cur = cur->next;
            pre = pre->next;
        }

        return pre->next;
    }
};

和力扣删除倒数第k个节点相似,不过本题需要判断k的值是否会大于链表长度,所以在cur指针移动的时候需要进行判断

Day2