Remove Nth Node from End of List

Source: Internet
Author: User

    /** 19.     Remove Nth node from end of the List * 2016-4-15 by Mingyang * The last n points are not good, but you can start with the nth point from the front to set a fast Node, and then a slow node. * However, it is important to note that if fast moves n and then becomes null, it means that the head must be removed.*/     Public StaticListNode RemoveNthFromEnd11 (ListNode head,intN) {if(head==NULL|| N<0)           return NULL; if(n==0)          returnHead; ListNode Slow=Head; ListNode Fast=Head;  while(n>0&&fast!=NULL) {Fast=Fast.next; N--; }         if(n>0)           returnHead; if(n==0&&fast==NULL)           returnHead.next;  while(fast.next!=NULL) {Fast=Fast.next; Slow=Slow.next; } Slow.next=Slow.next.next; returnHead; }    /** Above is my code, the following is someone else's code, more neat, * because the problem reduced the difficulty: Given n would always be valid. * So n greater than the length of the condition will not have to determine the * special case is: The second 1 remove the first and other * summed up is only 1 remove this one, a lot of but remove the first, other situations */     PublicListNode Removenthfromend (ListNode head,intN) {ListNode slow=Head; ListNode Fast=Head; if(Head.next = =NULL)            return NULL;//1 Remove the first one         for(inti = 1; I <= N; i++) {Fast=Fast.next; }        //Remove the second one        if(Fast = =NULL) {Head=Head.next; returnHead; }         while(Fast.next! =NULL) {Fast=Fast.next; Slow=Slow.next; } Slow.next=Slow.next.next; returnHead; }

Remove Nth Node from End of List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.