Skip to content

Latest commit

 

History

History
42 lines (35 loc) · 1 KB

19.md

File metadata and controls

42 lines (35 loc) · 1 KB

Leetcode 19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
  let newHeadList = new ListNode();
  newHeadList.next = head;

  // 两个指针 fast、slow 分别都指向新链表的头
  let fast = newHeadList;
  let slow = newHeadList;

  // 往后移动 fast 指针,使 fast、slow 间隔 n
  for (let i = 0; i < n + 1; i++) {
    fast = fast.next;
  }

  // 同时移动 fast、slow 指针,当 fast 到达链表尾部时停止
  while (fast != null) {
    fast = fast.next;
    slow = slow.next;
  }

  // 删除 slow 指针后面的元素
  slow.next = slow.next.next;
  return newHeadList.next;
};