Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
判断链表是否回文,先把链表从中间分成两半,然后将其中一条链表倒置,再进行比较。
第一步,用slow和fast的方式,将链表分成两半,注意需要用一个pre来表示第一个链表最后一个节点,然后将其next设为None。
第二步,链表倒置。
第三步,比较两个链表的值是否相等,完全遍历完则返回True。(可能有一个链表还没遍历完,此时说明原链表为奇数个node,所以仍然返回True)
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None or head.next is None:return True
fast=slow=head
while fast and fast.next:
pre=slow
slow=slow.next
fast=fast.next.next
pre.next=None
tmp=None
while slow:
cur=slow
slow=slow.next
cur.next=tmp
tmp=cur
while tmp and head:
if tmp.val==head.val:
tmp=tmp.next
head=head.next
else:return False
return True