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.
Test instructions: Give a list to delete the nth node of the bottom
Just read this problem in the book, the idea is to use a double pointer, P1,P2, first let P2 walk n step, and then p1,p2 a walk, when the P2 stopped,
P1->next just points to the node you want to delete, but be aware that:
When P2 stops, N does not become 0, this is the time to verify the value of N, when n>0, the node that P1 points to is the node to be deleted
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * struct ListNode *next;6 * };7 */8 structlistnode* Removenthfromend (structListnode* Head,intN) {9 if(head==NULL)Ten returnhead; One structListNode *p1,*p2,*tmp; Ap1=head; -P2=head; - while(n>0&&p2->next!=NULL) { theP2=p2->Next; -n--; - } - if(n>0){ +tmp=P1; -Head=p1->Next; + Free(TMP); A } at Else - { - while(p2->next!=NULL) { -P2=p2->Next; -P1=p1->Next; - } inTmp=p1->Next; - if(tmp!=NULL) { toP1->next=tmp->Next; + Free(TMP); - } the } * returnhead; $}
"Leetcode" 19. Remove Nth Node from End of List