# 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 # 则为回文链表
# 找到链表中点
slow = fast = head
while fast.next and fast.next.next: # 使用快慢指针找到链表的中点
slow = slow.next
fast = fast.next.next
# 反转后半部分链表
prev = None
curr = slow.next
while curr: # 反转链表
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
# 反转后的部分链表头为prev
# 比较前半部分和反转后的后半部分
left, right = head, prev
while right: # 比较两部分链表是否相同
if left.val != right.val: # 如果值不相等
return False # 则不是回文链表
left = left.next
right = right.next
return True # 链表为回文链表
leetcode-回文链表
最新推荐文章于 2024-07-12 21:04:18 发布