# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defisPalindrome(self, head):"""
:type head: ListNode
:rtype: bool
"""
num_list =list()
p = head
while p:
num_list.append(p.val)
p = p.next
flag =Truefor i inrange(len(num_list)/2):if num_list[i]!= num_list[-(i+1)]:
flag =Falsereturn flag
自己2:反转链表法
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defisPalindrome(self, head):"""
:type head: ListNode
:rtype: bool
"""ifnot head ornot head.next:returnTrue
slow = head
fast = head.next
pre = prepre =Nonewhile fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
pre.next= prepre
print(pre)
prepre = pre
p2 = slow.next
slow.next= pre
if fast:
p1 = slow
else:
p1 = slow.nextwhile p1:if p1.val != p2.val:returnFalse
p1 = p1.next
p2 = p2.nextreturnTrue