# 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: ListNode) -> bool:
arr = []
while head:
arr.append(head.val)
head = head.next
if arr[::-1] == arr:
return True
else:
return False
# 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: ListNode) -> bool:
self.pre_node = head
def res_check(node = head):
if node:
if not res_check(node.next):
return False
if self.pre_node.val != node.val:
return False
self.pre_node = self.pre_node.next
return True
return res_check()
# 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: ListNode) -> bool:
def reserve(head):
previous = None
current = head
while current:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous
# 初始化快慢结点
slow = fast = head
while fast and fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# slow到中点,翻转后面
after_reverse = reserve(slow.next)
# 判断两段是否相等
after_head = after_reverse
pre_head = head
while after_head and pre_head:
if after_head.val != pre_head.val:
return False
after_head = after_head.next
pre_head = pre_head.next
return True