# 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 not head:
return True
# res = []
# while head:
# res.append(head.val)
# head = head.next
#找中点
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
pre = None
cur = slow.next
slow.next = None
#翻转链表
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
#比较翻转后和翻转前是不是相同
while pre:
if head.val != pre.val:
return False
head = head.next
pre = pre.next
return True
# return res==res[::-1]
- 笨方法就不说了不满足空间复杂度
- 先找链表的中点
- 然后翻转链表中点以后的的链表
- 然后和链表从尾到头进行比较,如果相同就是回文链表,如果不同不是
总结:这是一个简单题目,但是考察的内容却比较多,因为要求的空间复杂度,因此必须使用双指针,找中点是一个考点,翻转链表就是另一个考点了。