LeetCode 题解工作台

回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为 回文链表 。如果是,返回 true ;否则,返回 false 。 示例 1: 输入: head = [1,2,2,1] 输出: true 示例 2: 输入: head = [1,2] 输出: false 提示: 链表中节点数目在范围 [1, …

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 链表指针操作

bolt

答案摘要

我们可以先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。 时间复杂度 ,其中 为链表的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false

 

示例 1:

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

示例 2:

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

 

提示:

  • 链表中节点数目在范围[1, 105]
  • 0 <= Node.val <= 9

 

进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

lightbulb

解题思路

方法一:快慢指针

我们可以先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。

时间复杂度 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
17
18
19
20
21
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        slow, fast = head, head.next
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        pre, cur = None, slow.next
        while cur:
            t = cur.next
            cur.next = pre
            pre, cur = cur, t
        while pre:
            if pre.val != head.val:
                return False
            pre, head = pre.next, head.next
        return True
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    They mention a follow-up about constant extra space, which strongly points to reversing the second half in place.

  • question_mark

    They ask how you would find the middle in one pass, signaling the slow and fast pointer setup.

  • question_mark

    They probe odd-length behavior, which means they want to see whether you know when the middle node should be skipped.

warning

常见陷阱

外企场景
  • error

    Starting comparison from the wrong middle position, especially on odd-length lists where the center node should not be matched against anything.

  • error

    Reversing the list incorrectly by losing the next pointer, which breaks the second half before comparison even starts.

  • error

    Comparing until the original tail length instead of the reversed half length, which can create false mismatches or null-pointer errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Restore the linked list after checking by reversing the second half back to its original order.

  • arrow_right_alt

    Solve the same palindrome check recursively, using call stack depth to simulate symmetric traversal from both ends.

  • arrow_right_alt

    Discuss a read-only interpretation where mutation is disallowed, making the stack or array approach the safer choice.

help

常见问题

外企场景

回文链表题解:链表指针操作 | LeetCode #234 简单