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
相关推荐
d111111111d27 分钟前
STM32-UART封装问题解析
笔记·stm32·单片机·嵌入式硬件·学习·算法
m0_6245785931 分钟前
MySQL主从复制支持跨版本吗_不同版本间同步的注意事项
jvm·数据库·python
yuanpan1 小时前
Python Pygame 入门教程:从零学会创建窗口、绘图和游戏交互
python·游戏·pygame
2401_871492851 小时前
如何在 React Router v6 中正确配置多路由组件显示
jvm·数据库·python
Jiangxl~2 小时前
IP数据云如何为不同行业提供精准IP查询与风险防控解决方案?
网络·网络协议·tcp/ip·算法·ai·ip·安全架构
神仙别闹2 小时前
基于Python(Django)+MySQL 实现(Web)SQL智能检测系统的设计与实现
python·mysql·django
甄心爱学习2 小时前
【项目实训】法律文书智能摘要系统4
python·github·个人开发
李伟_Li慢慢2 小时前
wolfram详解山峦算法
前端·算法
huzhongqiang2 小时前
Playwright理解与封装
python
zhangchaoxies3 小时前
MySQL触发器能否监控特定用户操作_结合审计功能实现分析
jvm·数据库·python