Remove Nth Node from End of List
O (n) complexity
1. Create a new head node as the virtual head so that there are no special cases to consider during the deletion process (the first node is deleted)
2. With two pointers p and Q, when P has gone N-step, in the same time to let PQ go backwards, when p goes to the end is null, Q points to the number of the last nth, the process of recording Father node, directly modify the pointer can be
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Removenthfromend (listnode* head,intN) { AListNode *p, *q,*Pre; -ListNode * node =NewListNode (0);//Add a virtual head node -Node->next =head; thePre =node; -p = q =head; - if(Head==null)returnNULL; - intI=0; + //Add a head node here for easy comprehension and easy removal - //with two pointers p and Q, when P has gone n steps, when the PQ is left at the same time, when P goes to the end null, Q points to the number of reciprocal nth + //in the process of recording the Father node, directly modify the pointer can A while(p!=NULL) { at if(i>=N) { -Pre =Q; -q= q->Next; - } -i++; -P=p->Next; in } -Pre->next = q->Next; to Free(q); + returnNode->Next; - } the};
Leetcode Remove Nth Node from End of List