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
相关推荐
liminla!6 小时前
SQL 从入门到进阶:语法速查与实战练习(完整优化版)
数据库·sql·算法
卡提西亚6 小时前
FastAPI基础入门
python·fastapi
fanruitian6 小时前
python 机器学习 ML LinearRegression KNN KMeans
python·机器学习·kmeans
鱼宵6 小时前
取集合第一个元素,Java 为什么要写三种写法?
java·windows·python·java21
卷无止境7 小时前
给AI装上一双眼睛:快速构建代码验证器的思路与落地方案
后端·python
维克兜率天7 小时前
【维克】指数调整:哪些股票会被“强制买入“?
人工智能·python·算法
come112347 小时前
Codex 下不同场景 模式选择
python
罗西的思考8 小时前
【轻量化复刻大模型】线性注意力交互式演示
人工智能·算法·机器学习
神也畏惧菠萝8 小时前
Day08 Python流程控制从入门到上瘾:if/match/while/for四件套,从B站登录一路打到猜数字游戏
python·算法·数据存储·for·while·if·ifelse