方法:快慢指针,快的先走
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre=new ListNode(0); //头节点前设置指针
pre.next=head; //从头开始
ListNode start=pre;
ListNode end=pre;
while(n!=0){ //n个节点
start=start.next;
n--;
}
while(start.next!=null){
start=start.next;
end=end.next;
}
end.next=end.next.next;
return pre.next; //指向头节点开始
}
}