import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
// 特殊情况,删除第一个节点,它没有前驱节点
int index = size(head) - n;
if(index == 0){
head = head.next;
return head;
}
// 找到前驱节点
ListNode prev = findNode(head, index - 1);
//ListNode cur = findNode(head, index);
// 修改前驱节点,指向下一节点的next
prev.next = prev.next.next;
return head;
}
// 寻找index处的节点,0<=index<size(head)
public ListNode findNode(ListNode head, int index) {
int cnt = 0;
ListNode p = head;
while(p != null && cnt != index) {
p = p.next;
cnt++;
}
return p;
}
// 求链表长度
public int size(ListNode head) {
int cnt = 0;
ListNode p = head;
while(p != null) {
p = p.next;
cnt++;
}
return cnt;
}
}