Skip to content

Latest commit

 

History

History
46 lines (41 loc) · 1.05 KB

19.remove-nth-node-from-end-of-list.md

File metadata and controls

46 lines (41 loc) · 1.05 KB

删除链表的倒数第N个节点

题目

思路

链表实际上就是一维有序数组, 要移除倒数第N个节点, 只需做以下步骤:

  1. 链表指针从头移到尾
  2. 开始往上回去N个节点.
  3. 该节点即需要删除的节点.
  4. 找到该节点, 将上个节点的next值改为当前节点的next值, 即可移除该节点.
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
  let curr = head
  const listNodes = [ head ]
  while (curr.next) {
    curr = curr.next
    listNodes.push(curr)
  }
  const { length } = listNodes
  const index = length - n - 1
  if (index > 0) {
    listNodes[index].next = listNodes[index + 1].next
  } else if (index < 0) {
    return head.next
  } else {
    head.next = head.next.next
    return head
  }
  return head
};