LeetCode 题解工作台

反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 示例 1: 输入: head = [1,2,3,4,5] 输出: [5,4,3,2,1] 示例 2: 输入: head = [1,2] 输出: [2,1] 示例 3: 输入: head = [] 输出: [] 提示: 链表中节点的数…

category

2

题型

code_blocks

8

代码语言

hub

2

相关题

当前训练重点

简单 · 链表·链表

bolt

答案摘要

我们创建一个虚拟头节点 ,然后遍历链表,将每个节点依次插入 的下一个节点。遍历结束,返回 。 时间复杂度 ,其中 为链表的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表·链表 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你单链表的头节点 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

 

进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?

lightbulb

解题思路

方法一:头插法

我们创建一个虚拟头节点 dummy\textit{dummy},然后遍历链表,将每个节点依次插入 dummy\textit{dummy} 的下一个节点。遍历结束,返回 dummy.next\textit{dummy.next}

时间复杂度 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 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
speed

复杂度分析

指标
时间O(n)
空间O(1) for the iterative solution
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

反转链表题解:链表·链表 | LeetCode #206 简单