编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
先用双指针找出链表中点,再将后半部分翻转,再对比两个部分链表。
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head == None or head.next == None:
return True
if head.next.next == None:
if head.val == head.next.val:
return True
else:
return False
#找中点
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
#翻转
pre = None
cur = slow.next
while cur!=None:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
#比较
while pre != None:
if head.val != pre.val:
return False
head = head.next
pre = pre.next
return True