返回

链表:删除链表节点的倒数第N个节点的JavaScript解法

前端

前言

算法问题一直是程序员面试中的常客,其中,链表问题更是算法面试中的重中之重。链表作为一种重要的数据结构,在现实生活中有着广泛的应用,它可以用来存储各种类型的数据,如字符串、数字、对象等。因此,熟练掌握链表问题的解法对于程序员而言至关重要。

在LeetCode算法题库中,删除链表节点的倒数第N个节点是一个基础算法题,考察了程序员对链表的基本操作和算法思路的理解。这道题的解法并不复杂,但需要清晰的思路和严谨的逻辑。

解题思路

删除链表节点的倒数第N个节点,可以采取以下步骤:

  1. 从链表头结点开始遍历链表,并统计链表的长度。
  2. 计算出链表长度减去N后的值,即倒数第N个节点在链表中的位置。
  3. 再次从链表头结点开始遍历链表,当遍历到倒数第N个节点时,删除该节点并返回新的链表头结点。

代码实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * Given the head of a linked list, remove the nth node from the end of the list and return its head.
 *
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
const removeNthFromEnd = (head, n) => {
  // Calculate the length of the linked list
  let length = 0;
  let currentNode = head;
  while (currentNode) {
    length++;
    currentNode = currentNode.next;
  }

  // Find the node to be deleted
  let indexToRemove = length - n;
  currentNode = head;
  let previousNode = null;
  let index = 0;
  while (currentNode) {
    if (index === indexToRemove) {
      // Delete the node
      if (previousNode) {
        previousNode.next = currentNode.next;
      } else {
        head = currentNode.next;
      }
      break;
    }
    previousNode = currentNode;
    currentNode = currentNode.next;
    index++;
  }

  return head;
};

练习题

  1. 实现一个函数,删除链表节点的倒数第M个节点和倒数第N个节点,M和N均为正整数,且M<N。
  2. 实现一个函数,删除链表中所有值为X的节点。
  3. 实现一个函数,将链表反转。

总结

删除链表节点的倒数第N个节点是LeetCode算法题库中的一道基础算法题,考察了程序员对链表的基本操作和算法思路的理解。通过清晰的思路和严谨的逻辑,可以轻松掌握该算法的实现技巧。希望本文能够帮助读者更好地理解链表问题,并为今后的算法面试做好准备。