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
相关推荐
Darkwanderor13 分钟前
高精度计算——基础模板整理
c++·算法·高精度计算
枫叶林FYL17 分钟前
第10章 符号推理与神经符号AI
pytorch·python·深度学习
普马萨特27 分钟前
基站 / WiFi 粗略位置对 A-GNSS 的影响
网络·人工智能·算法
py有趣40 分钟前
力扣热门100题之接雨水
算法·leetcode
nimadan121 小时前
剧本杀app2025推荐,多类型剧本体验与社交互动优势
人工智能·python
mmz12071 小时前
深度优先搜索DFS(c++)
c++·算法·深度优先
HAPPY酷1 小时前
Python高阶开发:从底层原理到架构设计的进阶之路
开发语言·python
疯狂打码的少年2 小时前
【Day 6 Java转Python】字符串处理的“降维打击”
java·开发语言·python
2301_764441332 小时前
家国同构模型:计算社会学的创新探索
python·数学建模
汀、人工智能2 小时前
[特殊字符] 第103课:单词搜索II
数据结构·算法·均值算法·前缀树·trie·单词搜索ii