解题思路

  1. 暴力法 先遍历一遍链表获取链表的size , size - n 得到的就是 应删除节点的前置节点 , 如若这个前置节点为0 ,则应该删除头节点, 若不为0 直接删除 size - n 的next 节点
  2. 快慢指针法 设置快慢指针fast 和slow , fast比slow 先走n个节点,当fast 为0时,slow 正处于 应删节点的前置节点, 我们直接删除 slow节点的 next节点就可以了

1. 暴力法

  1. /*
  2. * @lc app=leetcode.cn id=19 lang=javascript
  3. *
  4. * [19] 删除链表的倒数第N个节点
  5. */
  6. // @lc code=start
  7. /**
  8. * Definition for singly-linked list.
  9. * function ListNode(val) {
  10. * this.val = val;
  11. * this.next = null;
  12. * }
  13. */
  14. /**
  15. * @param {ListNode} head
  16. * @param {number} n
  17. * @return {ListNode}
  18. */
  19. var removeNthFromEnd = function (head, n) {
  20. if (!head.next || !head) return null
  21. let p = head
  22. let size = 0
  23. while (p) {
  24. size++
  25. p = p.next
  26. }
  27. if (n > size) return null
  28. size = size - n
  29. if (size == 0) {
  30. return head.next
  31. }
  32. p = head
  33. while (--size) {
  34. p = p.next
  35. }
  36. const deleteNode = p.next
  37. p.next = deleteNode.next
  38. return head
  39. }
  • 时间复杂度为 O(n)
  • 空间复杂度为 O(1)

2. 快慢指针法

  1. /*
  2. * @lc app=leetcode.cn id=19 lang=javascript
  3. *
  4. * [19] 删除链表的倒数第N个节点
  5. */
  6. // @lc code=start
  7. /**
  8. * Definition for singly-linked list.
  9. * function ListNode(val) {
  10. * this.val = val;
  11. * this.next = null;
  12. * }
  13. */
  14. /**
  15. * @param {ListNode} head
  16. * @param {number} n
  17. * @return {ListNode}
  18. */
  19. var removeNthFromEnd = function (head, n) {
  20. if (!head.next || !head) return null
  21. let fast = (slow = head)
  22. while (n--) {
  23. fast = fast.next
  24. }
  25. if (!fast) return head.next
  26. while (fast.next) {
  27. fast = fast.next
  28. slow = slow.next
  29. }
  30. const deleteNode = slow.next
  31. slow.next = deleteNode.next
  32. return head
  33. }
  34. // @lc code=end
  • 时间复杂度 O(n)
  • 空间复杂度 O(1)