Given A linked list, remove the nth node from the end of the list and return its head.
For example,
n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Ideas:
The most basic way of thinking must be to use two pointers, one to walk n+1 step, then two at the same time, so the pointer must be to remove the pointer in the front of the grid.
The main problem is that if you want to delete the head node, go to the N-step of the time must be null, so to add a judgment, if you have not finished walking n+1 step encountered the first pointer to null, then return Head->next
Alas, this 1.1-point logical relationship has been dizzy for a long time. To analyze clearly before doing the problem, not every time just rely on the feeling ... The feeling is particularly unreliable at this boundary condition ...
ListNode *removenthfromend (ListNode *head,intN) {ListNode* P1 = head, * p2 =Head; N++; while(n--//p1 Go first n+1 step {p1= p1->Next; if(P1 = = NULL && n! =0)//encountered the deletion of the head pointerreturnHead->Next; } while(P1! =NULL)//p1 go to the end, P2 just before the pointer you want to delete {P1= p1->Next; P2= p2->Next; } P2->next = p2->next->next;//delete the specified pointerreturnHead; }
"Leetcode" Remove Nth Node from End of List (easy)