返回
算法进阶指南:运用双指针技巧,轻松解决 LeetCode 第 19 题 —— 删除链表倒数第 N 个节点!
前端
2023-09-02 16:54:01
## LeetCode 19. 删除链表的倒数第 N 个节点
**问题** :
给你一个链表,删除链表的倒数第 `n` 个节点,并且返回链表的头结点。给定的 `n` 保证是有效的。
**示例** :
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
输入:head = [1], n = 1
输出:[]
**解题思路** :
这道题可以用双指针来实现。
1. 先用 `fast` 指针前进 `n` 步。
2. 然后让 `slow` 从 `head` 开始和 `fast` 一起前进,直到 `fast` 到了末尾,此时 `slow` 的下一个节点就是要删除的节点。
3. 删除 `slow` 的下一个节点,并返回 `head`。
**代码实现** :
```javascript
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* 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) => {
// Create two pointers, one slow and one fast.
let slow = head;
let fast = head;
// Move the fast pointer n steps ahead.
for (let i = 0; i < n; i++) {
fast = fast.next;
}
// If the fast pointer is null, it means we need to remove the head node.
if (fast === null) {
return head.next;
}
// Move both pointers until the fast pointer reaches the end of the list.
while (fast.next !== null) {
slow = slow.next;
fast = fast.next;
}
// The slow pointer is now pointing to the node before the node that needs to be removed.
slow.next = slow.next.next;
// Return the head of the modified list.
return head;
};
时间复杂度 :O(n),其中 n
是链表的长度。
空间复杂度 :O(1),因为我们只使用了两个指针。
结语
通过本题的讲解,希望你能对双指针技术有更深入的理解。算法进阶之路并非一帆风顺,但只要你坚持不懈,勇于探索,终将掌握更多奥妙技巧,成为算法高手!
关注我的博客,获取更多精彩算法解题技巧和深入剖析,不断提升你的算法能力,解锁更多编程难题!