快慢指针的做法,需要注意边界条件

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        int o = n;
        // write code here
        ListNode first = head, second = head, pre = null;
        while (first != null && n > 0) {
            n--;
            first = first.next;
        }
        while(first != null) {
            pre = second;
            first = first.next;
            second = second.next;
        }
        if (pre == null) {
            return head.next;
        }
        pre.next = pre.next.next;
        return head;
    }
}