难度简单12
编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
# 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
fast = head
slow = head
#慢指针为中间节点
while fast and fast.next:
slow = slow.next
fast = fast.next.next
pre = slow
#反转链表
while slow and slow.next:
tmp = slow.next.next
slow.next.next = pre
pre = slow.next
slow.next = tmp
#比较俩个部分的值
while head and pre:
if head.val != pre.val:
return False
head = head.next
pre = pre.next
return True
# 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:
dp =[]
p =head
while p:
dp.append(p.val)
p= p.next
return dp == dp[::-1]
# return dp == list(reversed(dp))