快慢指针分两半,然后逆序后半链表,之后对比
代码如下:

class Solution:
    def isPail(self , head: ListNode) -> bool:
        pre, slow, fast = head, head, head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        
        tail = self.reverseList(slow)
        while head and tail:
            if head.val != tail.val:
                return False
            head = head.next
            tail = tail.next
            
        return True
        
        
    def reverseList(self, head: ListNode) -> ListNode:
        p = head
        head = None
        while p:
            temp = p.next
            p.next = head
            head = p
            p = temp
            
        return head

我以为我嘎嘎聪明
一看评论区,存数组判断是否回文
是我反转链表反转魔怔了
代码如下:

class Solution:
    def isPail(self , head: ListNode) -> bool:
        n = []
        while head:
            n.append(head.val)
            head = head.next
        
        i, j = 0, len(n) - 1
        while i != j:
            if n[i] != n[j]:
                return False
            i += 1
            j -= 1
            
            if i - j == 1:      # 如果数组中元素为偶数个
                break
            
        return True