/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <cstdio>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param n int整型
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int n) {
        int len = 0;

        ListNode* tmp = pHead;
        while (tmp != nullptr) {
            len++;
            tmp = tmp->next;
        }
        int seq = len - n;
        tmp = pHead;
        ListNode* pre = nullptr;
        
        while (seq--) {
            pre = tmp;
            tmp = tmp->next;
        }
        return pre;
    }
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* pre = FindKthToTail(head, n);
        if(pre == nullptr){
            ListNode* cur = head->next;
            return cur;
        }
        else{
            ListNode* cur = pre->next;
            pre->next = cur->next;
            return head;
        }
        
    }
};