19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode) (leetcode-cn.com)

image.png
思路:
①添加一个前置虚节点,指向head,避免各种空指针的问题
②采用快慢指针法,快指针先走n步,假设总长度为len,还差len-n步走完,刚好,这几步和慢指针一起走,慢指针从头开始,走到第len-n个节点,即倒数第n个
代码:
public ListNode removeNthFromEnd(ListNode head, int n) {
// if(head==null || head.next==null) return new ListNode();
ListNode dump = new ListNode(0,head);
ListNode fast = dump ;
for(int i=0;i<n;i++){
fast = fast.next;
}
ListNode slow = dump;
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
//删除slow
slow.next = slow.next.next;
return dump.next;
}