请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
# 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 or not head.next: # 若链表为空或者只有一个节点,返回True
return True
# 快慢指针找中间节点
fast = head
slow = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# 此时slow指针指向中间节点
# 翻转slow指针后面的链表
pre = None
cur = slow.next
post = cur.next
while cur:
cur.next = pre
pre = cur
cur = post
if post:
post = post.next
# 此时pre指向最后一个节点
# 比较链表
while pre and head:
if pre.val == head.val:
pre = pre.next
head = head.next
else:
return False
return True