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
相关推荐
小师兄吃牛肉11 分钟前
Java语法 | 多重循环
java·开发语言·python
明如正午38 分钟前
用 Python 一键把 ASC 文件转成 BLF(基于 python-can)
python·can·blf·asc
jidaowansui1 小时前
B3643 图的存储———>数组模拟邻接矩阵
算法
y1su1 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
youshi66681 小时前
平衡车——PID算法优化
stm32·单片机·嵌入式硬件·算法·pid·平衡车
leisoo80971 小时前
融资融券数据怎么查两融指标含义与杠杆观察方法 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·json
Patrick在香港1 小时前
同一份脚本,mac 正常 Windows 乱码:open() 默认编码实测(附 3.15 终局)
utf-8·windows·python·macos·跨平台·编码·标准库
勿信日志2 小时前
Playwright 元素定位:一个 width>50 过滤器把 42px 的输入框删掉了
python
larance2 小时前
[菜鸟教程] 机器学习教程十课-Python 机器学习应用
人工智能·python·机器学习
栖凤2 小时前
Java 的 try-catch 在 Agent 里失效了,我用了 5 个模式才兜住
java·前端·python