法1:辅助数组,转化为数组问题。时间O(n),空间O(n)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head==None or head.next==None:
return True
arr=[]
while head:
arr.append(head.val)
head=head.next
return arr==arr[::-1]
法2: 利用快慢指针找到链表的中点,将链表的后半部分反序后和链表的前半部分进行一一对比。时间O(n),空间O(1)
另一种思路:利用快慢指针找到链表的中点,在找的过程中同时将慢指针处的值存入stack,利用stack的后进先出特性,将链表后 半部分和栈中值进行比较
注:快慢指针:快指针每次走两步,慢指针每次走一步,当快指针走完时慢指针刚好在中点处
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head==None or head.next==None:
return True
fast=slow=q=head
while fast and fast.next:
slow=slow.next #停止后slow处为中点
fast=fast.next.next
p=self.reverseList(slow) #p为后半部分链表反序后的head
while p:
if p.val != q.val:
return False
p=p.next
q=q.next
return True
def reverseList(self,head):
pre=None
cur=head
tmp=None
while cur:
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return pre