19. 删除链表的倒数第 N 个结点
    难度中等
    给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

    示例 1:
    输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
    示例 2:
    输入:head = [1], n = 1 输出:[]
    示例 3:
    输入:head = [1,2], n = 1 输出:[1]

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public ListNode removeNthFromEnd(ListNode head, int n) {
    13. if(head == null) return null;
    14. ListNode fast = head ,slow = head;
    15. while(n>0){
    16. fast = fast.next;
    17. n--;
    18. }
    19. if(fast == null) return head.next;
    20. while(fast.next != null){
    21. fast = fast.next;
    22. slow = slow.next;
    23. }
    24. slow.next = slow.next.next;
    25. return head;
    26. }
    27. }