
image.png
很明显是快慢指针法可以写的,这个不是难点,要注意的是,如果要删除第一个节点,快指针会已经跑到了null,所以如果当快指针到了null,n还没有减完的话,就是要删除头节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast=head;
ListNode slow =head;
while(n>=0){
if(fast==null) return slow.next;
fast=fast.next;
n--;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;
return head;
}
}