import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
// 添加表头;许多都需要虚拟表头,以免涉及到表头的问题比较复杂。
ListNode res = new ListNode(-1);
res.next = head;
if(head==null){
return null;
}
ListNode s = head;
ListNode f = head;
//前序节点,记录倒数第n个节点的头一个节点
ListNode pre = res;
while(n>0){
f = f.next;
n--;
}
//同时走此时s在的位置就是倒数第n个节点,所以需要前序节点记录倒数第n个节点的前一个。
while(f!=null){
f = f.next;
pre = s;
s = s.next;
}
pre.next = s.next;
return res.next;
}
}