描述

给你一个链表,删除链表的倒数第 n个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?

示例 1:

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

示例 2:

输入:head = [1], n = 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. const dummyHead = new ListNode(0, head);
  15. let fast = dummyHead,
  16. slow = dummyHead;
  17. for (let i = 0; i <= n; i++) {
  18. fast = fast.next;
  19. }
  20. while (fast) {
  21. slow = slow.next;
  22. fast = fast.next;
  23. }
  24. slow.next = slow.next.next;
  25. return dummyHead.next
  26. };