Given A linked list, remove the nth node from the end of the list and return its head.
For example.
1,2,3,4,52from1 2,3,5.
The topic is simple, set two pointers separated by N-1, walk together, walk after a pointer goes to the head, the previous pointer is exactly where you want to delete the node. Pay attention to the case that the list length is less than N.
My Code:
/** * Definition for singly-linked list.* struct ListNode {* int val;* listnode *next;* listnode (int x): Val (x), Next (NULL) {}*};*/classSolution { Public: ListNode* Removenthfromend (listnode* head,intN) {if(head = = NULL | | n = =0) returnHead; ListNode*PF, *pl,*temp=NULL; PF= PL =Head; inti =0; for(; i < n-1; ++i) { if(pl->next) Pl= pl->Next; Else returnHead; } while(pl->next) {Temp=PF; PL= pl->Next; PF= pf->Next; } if(temp = =NULL) {Head= pf->Next; DeletePF; } Else{Temp->next = pf->Next; DeletePF; } returnHead; }};
#19 Remove Nth Node from End of List