Leetcode 234. Palindrome Linked List

Problem

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Algorithm

Use a double-step pointer to find the start of the second half of the linked list (skip if counting), reverse the second half, then compare elements for validation.

Code

python3 复制代码
# 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:
        if not head or not head.next:
            return True

        p1, p2 = head, head
        while p2 and p2.next:
            p1 = p1.next
            p2 = p2.next.next

        if p2:
            p1 = p1.next
        
        p3, p4 = p1, None
        while p3:
            p0 = p3.next
            p3.next = p4
            p4 = p3
            p3 = p0
        
        p1, p2 = head, p4
        while p2:
            if p1.val != p2.val:
                return False
            p1, p2 = p1.next, p2.next

        return True
相关推荐
花酒锄作田4 小时前
Pydantic校验配置文件
python
hboot4 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
罗西的思考7 小时前
机器人 / 强化学习】HIL-SERL:人类在环驱动的具身智能进化框架
人工智能·算法·机器学习
美团技术团队10 小时前
LongCat 开源 VitaBench 2.0:长期动态智能体基准新标杆
人工智能·算法
ZhengEnCi15 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi17 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽17 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户83580861879118 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
To_OC1 天前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC1 天前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode