/** 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