/* * 19. Remove Nth Node From End of List * 2016-4-15 By Mingyang * 最后n个点不好算,但是可以从前面开始算第n个点定一个fast node,然后再来一个slow node。 * 不过需要注意的细节就是,如果fast移动n个以后变成了null就表明需要移除掉的就是head */ public static ListNode removeNthFromEnd11(ListNode head, int n) { if(head==null||n<0) return null; if(n==0) return head; ListNode slow=head; ListNode fast=head; while(n>0&&fast!=null){ fast=fast.next; n--; } if(n>0) return head; if(n==0&&fast==null) return head.next; while(fast.next!=null){ fast=fast.next; slow=slow.next; } slow.next=slow.next.next; return head; } /* * 上面是我的代码,下面是别人的代码,更整洁一点, * 因为题目把难度降低了:Given n will always be valid. * 这样n大于长度的条件就不用判定了 * 特殊case就是: 1,2 remove 第二个 1 remove 第一个 等 * 总结起来无非就是只有1个remove这一个,很多个但是remove第一个,其他情况 */
public static ListNode removeNthFromEnd(ListNode head, int n) { if(head == null || head.next == null) return null; ListNode faster = head; ListNode slower = head; for(int i = 0; i<n; i++) faster = faster.next; if(faster == null){ head = head.next; return head; } while(faster.next != null){ slower = slower.next; faster = faster.next; } slower.next = slower.next.next; return head; }