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 输…
2
题型
11
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们定义两个指针 `fast` 和 `slow`,初始时都指向链表的虚拟头结点 `dummy`。 接着 `fast` 指针先向前移动 步,然后 `fast` 和 `slow` 指针同时向前移动,直到 `fast` 指针到达链表的末尾。此时 `slow.next` 指针指向的结点就是倒数第 `n` 个结点的前驱结点,将其删除即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你一个链表,删除链表的倒数第 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 <= 300 <= Node.val <= 1001 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
解题思路
方法一:快慢指针
我们定义两个指针 fast 和 slow,初始时都指向链表的虚拟头结点 dummy。
接着 fast 指针先向前移动 步,然后 fast 和 slow 指针同时向前移动,直到 fast 指针到达链表的末尾。此时 slow.next 指针指向的结点就是倒数第 n 个结点的前驱结点,将其删除即可。
时间复杂度 ,其中 为链表的长度。空间复杂度 。
# 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.