给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
if not head.next:
return True
# 用于找到中间点的指针
slow = head
fast = head
# 用于反转的指针
pre = None
cur = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
cur.next = pre
pre = cur
cur = slow
#奇数情况
if fast:
slow = slow.next
while pre and slow:
if pre.val != slow.val:
return False
pre = pre.next
slow = slow.next
return True