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
相关推荐
故事和你919 小时前
sdut-程序设计基础Ⅰ-实验五一维数组(8-13)
开发语言·数据结构·c++·算法·蓝桥杯·图论·类和对象
像污秽一样9 小时前
算法与设计与分析-习题4.2
算法·排序算法·深度优先·dfs·bfs
Storynone10 小时前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
小鸡吃米…11 小时前
Python—— 环境搭建
python
io_T_T11 小时前
python 文件管理库 Path 解析(详细&基础)
python
明明如月学长11 小时前
AI 更新太快学不过来?我用OpenClaw打造专属AI学习工作流
算法
黎阳之光11 小时前
【黎阳之光:以无线专网与视频孪生,赋能智慧广电与数字中国】
算法·安全·智慧城市·数字孪生
刀法如飞12 小时前
Agentic AI时代,程序员必备的算法思想指南
人工智能·算法·agent
刀法如飞12 小时前
Agentic AI时代程序员必备算法思想详解(附实战案例)
算法·ai编程·编程开发·agentic
渔阳节度使12 小时前
SpringAI实时监控+观测性
后端·python·flask