LeetCode 题解工作台
反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 示例 1: 输入: head = [1,2,3,4,5] 输出: [5,4,3,2,1] 示例 2: 输入: head = [1,2] 输出: [2,1] 示例 3: 输入: head = [] 输出: [] 提示: 链表中节点的数…
2
题型
8
代码语言
2
相关题
当前训练重点
简单 · 链表·链表
答案摘要
我们创建一个虚拟头节点 ,然后遍历链表,将每个节点依次插入 的下一个节点。遍历结束,返回 。 时间复杂度 ,其中 为链表的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表·链表 题型思路
题目描述
head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000] -5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
解题思路
方法一:头插法
我们创建一个虚拟头节点 ,然后遍历链表,将每个节点依次插入 的下一个节点。遍历结束,返回 。
时间复杂度 ,其中 为链表的长度。空间复杂度 。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
dummy = ListNode()
curr = head
while curr:
next = curr.next
curr.next = dummy.next
dummy.next = curr
curr = next
return dummy.next
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) for the iterative solution |
面试官常问的追问
外企场景- question_mark
Do you know how to handle pointer updates safely without losing references to nodes?
- question_mark
Can you explain the difference in space complexity between the iterative and recursive solutions?
- question_mark
Are you familiar with edge cases such as empty lists or lists with only one element?
常见陷阱
外企场景- error
Failing to maintain the correct order of nodes during pointer reversal, leading to lost references.
- error
Overcomplicating the solution with extra data structures, which isn't needed for in-place reversal.
- error
Forgetting to handle the case where the list is empty or has only one node.
进阶变体
外企场景- arrow_right_alt
Reverse a doubly linked list in place.
- arrow_right_alt
Reverse a linked list in groups of k nodes.
- arrow_right_alt
Reverse a linked list in a more memory-efficient way using tail recursion.