1 classSolution {2 Public:3listnode* Removenthfromend (listnode* head,intN) {4 if(n<=0| |Head==null)returnhead;5ListNode Prehead (0);6prehead.next=head;7ListNode *p=head;8 intLength=0, I;9 while(p->next)Ten { Onelength++; AP=p->Next; - } -p=&Prehead; thelength++; - if(n>length) n=n%length; -i=length-N; - + while(i--) p=p->Next; - if(n==1) p->next=NULL; + ElseP->next=p->next->Next; A returnPrehead.next; at } -};
Efficiency is not high, or the previous ideas, no innovation, the following is someone else's a better
1 classSolution {2 Public:3listnode* Removenthfromend (listnode* head,intN) {4 if(n<=0| |Head==null)returnhead;5ListNode Prehead (0);6prehead.next=head;7ListNode *p=&Prehead;8head=&Prehead;9 while(n--)Ten { OneP=p->Next; A } - while(p->next) - { theP=p->Next; -Head=head->Next; - } -Head->next=head->next->Next; + - returnPrehead.next; + } A};
The first few can be used to make a mark, and then the other starts from the beginning, this continues until the end.
Remove Nth Node from End of List