题目描述

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

示例:

  1. 给定一个链表: 1->2->3->4->5, n = 2.

  2.  

  3. 当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

双指针,指针A先移动n次, 指针B再开始移动。当A到达null的时候, 指针b的位置正好是倒数n

我们可以设想假设设定了双指针p和q的话,当q指向末尾的NULL,p与q之间相隔的元素个数为n时,那么删除掉p的下一个指针就完成了要求。

设置虚拟节点dummyHead指向head

设定双指针p和q,初始都指向虚拟节点dummyHead

移动q,直到p与q之间相隔的元素个数为n

同时移动p与q,直到q指向的为NULL

将p的下一个节点指向下下个节点

 

关键点解析

  1.  

    链表这种数据结构的特点和使用

     

  2.  

    使用双指针

     

  3.  

    使用一个dummyHead简化操作

     

代码

  1. /*

  2. * @lc app=leetcode id=19 lang=javascript

  3. *

  4. * [19] Remove Nth Node From End of List

  5. *

  6. * https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

  7. *

  8. * algorithms

  9. * Medium (34.03%)

  10. * Total Accepted: 360.1K

  11. * Total Submissions: 1.1M

  12. * Testcase Example: '[1,2,3,4,5]\n2'

  13. *

  14. * Given a linked list, remove the n-th node from the end of list and return

  15. * its head.

  16. *

  17. * Example:

  18. *

  19. *

  20. * Given linked list: 1->2->3->4->5, and n = 2.

  21. *

  22. * After removing the second node from the end, the linked list becomes

  23. * 1->2->3->5.

  24. *

  25. *

  26. * Note:

  27. *

  28. * Given n will always be valid.

  29. *

  30. * Follow up:

  31. *

  32. * Could you do this in one pass?

  33. *

  34. */

  35. /**

  36. * Definition for singly-linked list.

  37. * function ListNode(val) {

  38. * this.val = val;

  39. * this.next = null;

  40. * }

  41. */

  42. /**

  43. * @param {ListNode} head

  44. * @param {number} n

  45. * @return {ListNode}

  46. */

  47. var removeNthFromEnd = function(head, n) {

  48. let i = -1;

  49. const noop = {

  50. next: null

  51. };

  52.  

  53. const dummyHead = new ListNode(); // 增加一个dummyHead 简化操作

  54. dummyHead.next = head;

  55.  

  56. let currentP1 = dummyHead;

  57. let currentP2 = dummyHead;

  58.  

  59.  

  60. while (currentP1) {

  61.  

  62. if (i === n) {

  63. currentP2 = currentP2.next;

  64. }

  65.  

  66. if (i !== n) {

  67. i++;

  68. }

  69.  

  70. currentP1 = currentP1.next;

  71. }

  72.  

  73. currentP2.next = ((currentP2 || noop).next || noop).next;

  74.  

  75. return dummyHead.next;

  76. };