//采用递归的方法先找出需要删除的结点所在的位置的前一个结点和后一个结点
//将前一个结点指向后一个结点,返回链表即可
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) {
    ListNode newHead = head;
    if (head == null || head.next == null) {
        return null;
    }
    int index = removeIndex(head) ;
    if (index == n) {
        newHead = head.next;
        head.next = null;
        return newHead;
    }
    ListNode before = head;
    while (index - n > 1) {
        before = before.next ;
        index--;
    }

    ListNode next = before.next;
    ListNode after = before.next.next;

    before.next = after;
    next.next = null;
    return newHead;


    // write code here
}

public int removeIndex(ListNode head) {
    int index = 1;
    while (head.next != null) {
        index++;
        head = head.next;
    }
    return index;
}

}