题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
代码随想录链接:https://programmercarl.com/0019.删除链表的倒数第N个节点.html#思路
/**
* 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 dump = new ListNode(-1, head);
ListNode slow = dump;
//因为fast需要多走n+1步,才能使得slow正好为我们要去除的节点的前一位
ListNode fast = dump.next;
while ((n--)>0 && fast != null) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dump.next;
}
}