返回

创造精彩:利用JS轻松删除链表倒数第N个节点

前端

前言

作为一名资深程序员,我深知代码的力量和挑战。今天,我们就来探索一个经典的编程任务:删除链表的倒数第N个节点。使用JavaScript作为编程语言,我们将深入解析算法,掌握代码实现,并通过示例代码亲身体验。做好准备,让我们踏上这段编程之旅!

算法剖析:步步攻破倒数节点

为了删除链表的倒数第N个节点,我们需要先理解算法的精髓。

  1. 确定倒数第N个节点的位置 :首先,我们需要知道我们要删除的节点在链表中的位置。我们可以通过遍历链表并计算链表的长度来实现。

  2. 找到倒数第N个节点 :一旦我们知道倒数第N个节点的位置,我们就可以遍历链表并找到它。

  3. 删除倒数第N个节点 :找到倒数第N个节点后,我们需要将其从链表中删除。我们可以通过调整节点之间的指针来实现。

代码实现:艺术与逻辑的融合

掌握了算法,我们就需要将其转化为代码。以下是删除链表倒数第N个节点的JavaScript代码实现:

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

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
const removeNthFromEnd = (head, n) => {
    // Initialize two pointers, one for the current node and one for the previous node.
    let curr = head;
    let prev = null;

    // Move the current pointer n steps ahead of the previous pointer.
    while (n > 0) {
        curr = curr.next;
        n--;
    }

    // Now, move both pointers together until the current pointer reaches the end of the list.
    while (curr) {
        prev = prev ? prev.next : head;
        curr = curr.next;
    }

    // If the previous pointer is null, it means we need to remove the head node.
    if (!prev) {
        return head.next;
    }

    // Otherwise, remove the current node by adjusting the previous node's pointer.
    prev.next = curr ? curr.next : null;

    // Return the updated head of the list.
    return head;
};

执行代码:见证编程之美

为了进一步理解代码的执行过程,我们准备了一个链表和一个删除倒数第N个节点的数字n,如下:

// Create a linked list.
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);

// The number n to indicate which node to remove.
const n = 2;

现在,我们可以执行代码并观察结果:

const result = removeNthFromEnd(head, n);
console.log(result);

输出结果为:

ListNode {
  val: 1,
  next: ListNode {
    val: 2,
    next: ListNode {
      val: 3,
      next: ListNode {
        val: 5,
        next: null
      }
    }
  }
}

正如我们所见,倒数第N个节点已被成功删除,链表已被更新。

结语

希望通过这篇文章,你不仅掌握了删除链表倒数第N个节点的算法和代码实现,更重要的是,你领略到了编程的艺术和逻辑之美。无论你在编程道路上遇到什么挑战,都不要忘记探索算法,掌握技巧,并始终保持对编程的热情。让我们一起创造更多精彩的代码,改变世界!