class Solution(object):
def isPalindrome(self, head):
“”"
:type head: ListNode
:rtype: bool
“”"
# second method
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
return True
# transform linked list to list, check list[::-1] and list
string = []
while head is not None:
string.append(head.val)
head = head.next
return string == string[::-1]`在这里插入代码片`