/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* cur = head;
        int length = 0;
        while(cur)
        {
            ++length;
            cur = cur->next;
        }
        if(length==n)
        {
            ListNode* temp = head;
            head=head->next;
            delete temp;
            return head;
        }
        length = length - (n+1);
        cur = head;
        while(length--)
        {
            cur = cur->next;
        }
        ListNode* temp = cur->next;
        cur->next = cur->next->next;
        delete temp;
        return head;
    }
};