# 删除链表的倒数第N个节点

1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

``````/**
* 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 dummy = new ListNode(0);
int length = 0;
ListNode cur = dummy;
while (cur.next != null) {
length++;
cur = cur.next;
}
if (n < 0 || n > length) {return null;}
cur = dummy;
for (int i = 0; i < length - n; i++) {
cur = cur.next;
}
cur.next = cur.next.next;
return dummy.next;
}
}
``````

``````/**
* 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 dummy = new ListNode(0);
ListNode slow = dummy;
ListNode fast = dummy;
//fast比slow先走n+1步
for (int i = 0; i < n + 1; i++) {
fast = fast.next;
}
//fast先走到尾部null的位置
//此时slow的位置即删除节点的前一个节点
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
``````