public ListNode RemoveNthFromEnd(ListNode head, int n) { if (head == null || n < 0 ) { return head; } ListNode pre = head, aft = null; for (int i = 0; i < n; ++i) { pre = pre.next; } while (pre != null) { pre = pre.next; if (aft == null) { aft = head; } else { aft = aft.next; } } if (aft == null) { head = head.next; } else { aft.next = aft.next.next; } return head; }
public ListNode(int x) { val = x; next = null; }