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
相关推荐
恒云客1 小时前
python uv debug launch.json
数据库·python·json
Katecat996631 小时前
YOLO11-SEG-AFPN-P345改进采血装置检测与识别系统
python
阿里云大数据AI技术2 小时前
阿里云PAI助力新一代Qwen3.5模型发布!
人工智能·算法
q1234567890982 小时前
FNN sin predict
开发语言·python
小白菜又菜2 小时前
Leetcode 221. Maximal Square
算法·leetcode·职场和发展
先做个垃圾出来………2 小时前
Python字节串“b“前缀
开发语言·python
流云鹤2 小时前
牛客周赛Round 132(无F)
算法
Lee川2 小时前
深入解析:从内存模型到作用域陷阱——JavaScript变量的前世今生
javascript·算法
㓗冽2 小时前
回文数2(字符串)-基础题97th + 加法器(字符串)-基础题98th + 构造序列(字符串)-基础题99th
算法