/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // write code here
        ListNode *p1,*p2;
        p1=head;
        p2=head;
        ListNode *pHead=new ListNode(0);//添加一个头结点便于后续处理
        pHead->next=head;
	  //找到倒数第n个结点
        for(int i=n-1;i>0;i--)
        {
            p2=p2->next;
        }
        while(p2->next!=nullptr)
        {
            p1=p1->next;
            p2=p2->next;
        }
	  //找到要删除的结点的前驱
        ListNode *q=pHead;
        while(q->next!=p1)
        {
            q=q->next;
        }
	  //删除该结点并返回新的链表
        q->next=p1->next;
        return pHead->next;//返回头结点的下一个结点(不能直接返回head,因为有可能head已经被删掉了)
    }
};