1.基本做法
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: Optional[ListNode]) -> bool:
vals=[]
p=head
while p!=None:
vals.append(p.val)
p=p.next
if len(vals)==1:
return True
elif (len(vals))%2==0:
j=(len(vals))//2
i=j-1
while i>=0 and j<len(vals) and vals[i]==vals[j]:
i=i-1
j=j+1
if i>=0:
return False
else :
return True
else :
j=(len(vals))//2+1
i=j-2
while i>=0 and j<len(vals) and vals[i]==vals[j]:
i=i-1
j=j+1
if i>=0:
return False
else :
return True
2.更简洁
# 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: Optional[ListNode]) -> bool:
vals=[]
p=head
while p:
vals.append(p.val)
p=p.next
left,right=0,len(vals)-1
while right>left:
if vals[right]!=vals[left]:
return False
right=right-1
left=left+1
return True