LeetCode 题解工作台
回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为 回文链表 。如果是,返回 true ;否则,返回 false 。 示例 1: 输入: head = [1,2,2,1] 输出: true 示例 2: 输入: head = [1,2] 输出: false 提示: 链表中节点数目在范围 [1, …
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 链表指针操作
答案摘要
我们可以先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。 时间复杂度 ,其中 为链表的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你一个单链表的头节点 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) 空间复杂度解决此题?
解题思路
方法一:快慢指针
我们可以先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。
时间复杂度 ,其中 为链表的长度。空间复杂度 。
# 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.