# 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:
# 前半部分和record list一样
if not head or not head.next:
return True
slow = head
fast = head.next
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
slow = slow.next
if fast.next:
fast = fast.next
pre = ListNode(-1)
pre.next = slow
cur = slow
nex = slow.next
while nex:
cur.next = nex.next
nex.next = pre.next
pre.next = nex
nex = cur.next
# 举例:1 2 3 4 5 经过上述操作,slow = 3,fast = 5且fast为头指针的链表为 5->4->3,以head为头指针的链表仍为 1 2 3 4 5
while head != fast: # 注意这里为判断结点相等,所以需要val和next都相等
if head.next == fast: # 结束循环的条件之一(当链表个数为偶数个时适用)解释见下
return head.val == fast.val
elif head.val != fast.val:
return False
else: # 承接第一个if,如1 2 2 1 fast:1 2 ,第一次循环head走到第一个1,fast走到1,进入else
fast = fast.next # 此时head为2 fast为2,下一轮循环时,如果没有第一个if,head会为第二个2,fast为None
head = head.next # 此时又满足循环条件,继续新一轮,但是此时fast已经为None没有next报错。所以加第一个if
return True
leetcode234(判断回文)
最新推荐文章于 2022-07-13 21:20:03 发布