LeetCode 题解工作台
反转链表 II
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。 示例 1: 输入: head = [1,2,3,4,5], left = 2, right = 4 输出: [1,4,3,2,5]…
1
题型
8
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
定义一个虚拟头结点 `dummy`,指向链表的头结点 `head`,然后定义一个指针 `pre` 指向 `dummy`,从虚拟头结点开始遍历链表,遍历到第 `left` 个结点时,将 `pre` 指向该结点,然后从该结点开始遍历 `right - left + 1` 次,将遍历到的结点依次插入到 `pre` 的后面,最后返回 `dummy.next` 即可。 时间复杂度 ,空间复杂度 。其中 为…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4 输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1 输出:[5]
提示:
- 链表中节点数目为
n 1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
解题思路
方法一:模拟
定义一个虚拟头结点 dummy,指向链表的头结点 head,然后定义一个指针 pre 指向 dummy,从虚拟头结点开始遍历链表,遍历到第 left 个结点时,将 pre 指向该结点,然后从该结点开始遍历 right - left + 1 次,将遍历到的结点依次插入到 pre 的后面,最后返回 dummy.next 即可。
时间复杂度 ,空间复杂度 。其中 为链表的长度。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(
self, head: Optional[ListNode], left: int, right: int
) -> Optional[ListNode]:
if head.next is None or left == right:
return head
dummy = ListNode(0, head)
pre = dummy
for _ in range(left - 1):
pre = pre.next
p, q = pre, pre.next
cur = q
for _ in range(right - left + 1):
t = cur.next
cur.next = pre
pre, cur = cur, t
p.next = pre
q.next = cur
return dummy.next
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each node is visited at most once during traversal and reversal. Space complexity is O(1) because the reversal is done in-place with only a few extra pointers regardless of list size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if the candidate handles edge cases like left == 1 or left == right.
- question_mark
Looks for in-place pointer manipulation without using extra arrays or stacks.
- question_mark
Monitors how well the candidate maintains connections before and after the reversed sublist.
常见陷阱
外企场景- error
Failing to handle the case where the reversal starts at the head node.
- error
Incorrectly reconnecting the reversed sublist to the remaining list, breaking links.
- error
Using extra memory instead of performing true in-place reversal.
进阶变体
外企场景- arrow_right_alt
Reverse nodes in groups of k instead of a single sublist, extending pointer manipulation skills.
- arrow_right_alt
Reverse a sublist with possible cycles in the linked list, requiring cycle detection.
- arrow_right_alt
Reverse only nodes with even values between left and right, combining conditional logic with pointer manipulation.