LeetCode 题解工作台

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

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 示例 1: 输入: head = [1,2,3,4,5], n = 2 输出: [1,2,3,5] 示例 2: 输入: head = [1], n = 1 输出: [] 示例 3: 输入: head = [1,2], n = 1 输…

category

2

题型

code_blocks

11

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们定义两个指针 `fast` 和 `slow`,初始时都指向链表的虚拟头结点 `dummy`。 接着 `fast` 指针先向前移动 步,然后 `fast` 和 `slow` 指针同时向前移动,直到 `fast` 指针到达链表的末尾。此时 `slow.next` 指针指向的结点就是倒数第 `n` 个结点的前驱结点,将其删除即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

 

示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

示例 2:

输入:head = [1], n = 1
输出:[]

示例 3:

输入:head = [1,2], n = 1
输出:[1]

 

提示:

  • 链表中结点的数目为 sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

 

进阶:你能尝试使用一趟扫描实现吗?

lightbulb

解题思路

方法一:快慢指针

我们定义两个指针 fastslow,初始时都指向链表的虚拟头结点 dummy

接着 fast 指针先向前移动 nn 步,然后 fastslow 指针同时向前移动,直到 fast 指针到达链表的末尾。此时 slow.next 指针指向的结点就是倒数第 n 个结点的前驱结点,将其删除即可。

时间复杂度 O(n)O(n),其中 nn 为链表的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(next=head)
        fast = slow = dummy
        for _ in range(n):
            fast = fast.next
        while fast.next:
            slow, fast = slow.next, fast.next
        slow.next = slow.next.next
        return dummy.next
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for knowledge of linked-list pointer manipulation.

  • question_mark

    Assess the candidate's understanding of two-pointer techniques.

  • question_mark

    Evaluate their handling of edge cases, such as small lists or when n is at list boundaries.

warning

常见陷阱

外企场景
  • error

    Not properly handling the edge case where the list has only one element or when n is equal to the list length.

  • error

    Failing to correctly update the next pointer of the node before the one to be removed.

  • error

    Misunderstanding the two-pointer technique and trying to manipulate the list in a less efficient way.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the list is cyclic? How would you handle that scenario?

  • arrow_right_alt

    Remove the nth node from the beginning or middle of the list instead of the end.

  • arrow_right_alt

    Modify the list such that it supports dynamic removals, rather than a fixed one-time operation.

help

常见问题

外企场景

删除链表的倒数第 N 个结点题解:链表指针操作 | LeetCode #19 中等