给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
复制代码
输入:head = [1,2,2,1]
输出:true
思路一:记录所有值到列表中,然后判断这些值是否为回文数。时间复杂度On,空间复杂度On.
python复制代码
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
arr = []
cur = head
while cur:
arr.append(cur.val)
cur = cur.next
return arr == arr[::-1]
思路二:空间复杂度O1
快慢指针 找到链表中点
反转后半段链表
前后两段逐一比
python复制代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return True
# 先找到中点
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
def reverse(node):
pre = None
while node:
tmp = node.next
node.next = pre
pre = node
node = tmp
return pre
second = reverse(slow)
# 前后半段逐一对比
p1, p2 = head, second
while p2:
if p1.val != p2.val:
return False
p1 = p1.next
p2 = p2.next
return True