Loading

[链表]判断回文链表

# 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:

        def findmid(head):
            fast = head
            slow = head
            while fast.next and fast.next.next:
                fast = fast.next.next
                slow = slow.next
            
            t = slow
            slow = slow.next
            t.next = None
            return t,slow

        tail,mid = findmid(head)

        cur = mid
        while cur:
            t = cur
            cur = cur.next
            t.next = tail.next
            tail.next = t

        mid = tail.next
        first = head

        while mid:
            if first.val != mid.val:
                return False
            mid = mid.next
            first = first.next
        return True
posted @ 2024-09-23 10:21  Duancf  阅读(12)  评论(0)    收藏  举报