/**
* 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 {
// 思路:1. 得出链表的长度,然后走size - n - 1,接着进行删除
// 2. 快慢指针,让快指针先走n步,之后慢指针再出发,
// 当快指针走到结尾的时候,慢指针指向的就是倒数第n个节点的前一个节点
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1,head);
ListNode fast = dummy;
ListNode low = dummy;
int count = 0;
while (fast.next != null) { // fast走到最后一个节点需要停下来
fast = fast.next;
count++;
if (count >= n + 1) {
low = low.next;
}
}
low.next = low.next.next;
return dummy.next;
// int size = 1;
// ListNode cur = head;
// while (cur.next != null) {
// cur = cur.next;
// size++;
// }
// if (n == size) return head.next; // 特判 n == size 的情况
// cur = head;
// for (int i = 1; i < size - n; i++) {
// cur = cur.next;
// }
// cur.next = cur.next.next;
// return head;
}
}