quantitatives-io-cQg7OxVWRPw-unsplash.jpg
简单给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

示例 1:
LC. 删除链表的倒数第N个节点 - 图2

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

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

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

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/linked-list/jf1cc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

代码

  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. let fast = head;
  15. let slow = head;
  16. // 快指针移动到慢指针的n个位置之后,慢指针还在初始位置
  17. while (n-- > 0) {
  18. fast = fast.next;
  19. }
  20. // 将快指针移动到末尾
  21. while (fast && fast.next) {
  22. fast = fast.next;
  23. slow = slow.next;
  24. }
  25. // 如果fast为null,则说明链表不够长
  26. if (fast === null) {
  27. return head.next;// null
  28. }
  29. slow.next = slow.next.next;
  30. return head;
  31. };

思路:快慢指针

  1. 首先我们令快慢指针都初始化为head;
  2. 快指针移动到慢指针n个位置之后
  3. 进行判断,若快指针为null则说明链表不够长,只能返回head.next,即null;
  4. 若链表长度足够则根据链表的性质,直接将slow.next指向为slow.next.next;