题解可以参考BM8 在那个基础上找到要删除节点的前一位。
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) {
// write code here
ListNode slow = head;
ListNode fast = head;
ListNode pre = null;
int i=0;
while(fast!=null){
fast = fast.next;
if(i>=n){
pre = slow;
slow = slow.next;
}
i = i+1;
}
//删除second节点
if(pre != null) {
pre.next = pre.next.next;
} else {
//考虑删除头节点的情况
head = head.next;
}
return head;
}
}