双指针大法又显神通。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null)return null;
ListNode ret=new ListNode(-1);
ret.next=head;
ListNode p1=ret;
ListNode p2=ret;
int i=0;
while(i<n&&p2.next!=null){
p2=p2.next;
i++;
}
if(p2==null&&i!=n)return head;
while(p2.next!=null){
p1=p1.next;
p2=p2.next;
}
p1.next=p1.next.next;
return ret.next;
}
}