1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public class RemoveNthNodeFromEndOfList { public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null) { return null; } if(n == 0) return head; ListNode preHead = new ListNode(0); preHead.next = head; ListNode c1 = head; ListNode c2 = head; while (n > 0) { c2 = c2.next; n--; } if(c2 == null) { return head.next; } while(c2.next != null) { c1 = c1.next; c2 = c2.next; } c1.next = c1.next.next; return head; } }
|