给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

    示例 1:
    image.png

    输入: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. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * @param {ListNode} head
    10. * @param {number} n
    11. * @return {ListNode}
    12. */
    13. var removeNthFromEnd = function (head, n) {
    14. // 定义快慢指针,快指针先走,当为null时,慢指针为删除节点
    15. let fast = slow = head;
    16. // 先走n步
    17. for (let i = 0; i < n; i += 1) {
    18. fast = fast.next
    19. }
    20. if (fast == null) return head.next;
    21. // fast 往后走,存在时 慢指针继续
    22. while (fast && fast.next) {
    23. fast = fast.next;
    24. slow = slow.next;
    25. }
    26. slow.next = slow.next.next
    27. return head;
    28. };

    image.png